//LIGHTBOX
$(document).ready(function() {
    $(".lightbox").lightBox();
})

$(document).ready(function() {
//    $("#column-2.re_Group .sideList-01").height( $("#column-1").height()-72 );
})

//HEADER HOVER ACTIONS
$(document).ready(function() {
    var headerTempClass;
    $("#header .main-nav > li").hover(function(){
        $(this).addClass("over");
        var order = parseFloat($(this).closest("li").prevAll().length)+1;
        headerTempClass = $("#sub-header").attr("class");
        $("#sub-header").attr("class","border-link"+order);
    },function(){
        $(this).removeClass("over");
        var order = parseFloat($(this).closest("li").prevAll().length)+1;
        $("#sub-header").attr("class",headerTempClass);
    });
    
    $("#header .top-nav > li").hover(function(){
        $(this).addClass("over");
    },function(){
        $(this).removeClass("over");
    });
});

//HOME BOX
$(document).ready(function() {
    $(".nav-tab li").click(function(){
        $(this).addClass("on").siblings("li").removeClass("on");
        $(".home-box .inner > div").hide();
        $(".home-box .inner > div:eq("+ $(".nav-tab li.on").prevAll("li").length +")").show();
    });
});

//REFERENCE CYCLE
$(document).ready(function() {
    $("#refbox .thumbs li:first a").addClass("activeSlide");
    var showNextThumbID = 0;
    
    //thumb click
    $("#refbox .thumbs li a").click(function(){
        if(showNextThumbID!=0){ clearTimeout (showNextThumbID); }
        if($("#refbox #switching div").is(":animated")){ return false; }
        
        $(this).addClass("activeSlide").closest("li").siblings("li").find("a").removeClass("activeSlide");
        var order = $(this).closest("li").prevAll("li").length;
        $("#refbox #switching div.on").fadeOut(function(){
            $(this).removeClass("on");
            $("#refbox #switching div:eq("+order+")").fadeIn().addClass("on");
        });        
        $("#refbox #scrolling_thumbs div").animate({marginLeft:"-"+(Math.floor(order/4)*416)+"px"});
        showNextThumbID = setTimeout('$("#refbox #thumb_arrow_right").click()', 5000 );
    });
    
    //button next
    $("#refbox #thumb_arrow_right").click(function(){
        if($("#refbox .thumbs li:has(.activeSlide)").nextAll("li").length==0){
            $("#refbox .thumbs li:first a").click();
        } else {
            $("#refbox .thumbs li a.activeSlide").closest("li").next("li").find("a").click();
        }
    });
    
    //button prev
    $("#refbox #thumb_arrow_left").click(function(){
        if($("#refbox .thumbs li:has(.activeSlide)").prevAll("li").length==0){
            $("#refbox .thumbs li:last a").click();
        } else {
            $("#refbox .thumbs li a.activeSlide").closest("li").prev("li").find("a").click();
        }
    });
    
    //set slideshow
    setTimeout('$("#refbox #thumb_arrow_right").click()', 5000 );
});

//ACCORDION
$(document).ready(function() {
    $(".text-accordion div div").hide();
    $(".text-accordion h2").click(function(){
        $(this).next("div").slideDown();
        $(this).closest("div").siblings().find("div").slideUp();
    });
    
    $(".jobs-accordion div div").hide();
    $(".jobs-accordion h3").click(function(){
        $(this).next("div").slideDown();
        $(this).closest("div").siblings().find("div").slideUp();
    });
});

//PAGING CLASSES
$(document).ready(function() {
    $(".pagination .buttons a").each(function(){
        if($(this).attr("href")==undefined){ $(this).addClass("off"); }
    });
})

//SEARCH

$(document).ready(function(){
    $("#searchForm select").not("[multiple]").each(function(){
        $(this).hide().after('<span class="sel-replaced'+(($(this).is(".off"))?" off":"")+'">'+$(this).find("option:selected").text()+'</span>');
    });
    $("#searchForm .sel-replaced:first").mightySelect("advanced","");
    $("#searchForm .sel-replaced").not(":first").mightySelect("advanced","dependable");
        
    $("#searchForm").submit(function(){
        $(this).find("input:text").each(function(){
            if($(this).val()==""){ $(this).attr("disabled","disabled"); }
        });
        $(this).find("select").each(function(){
            if($(this).val()==""||$(this).val()==null){ $(this).attr("disabled","disabled"); }
        });
    });
});


//GALLERY HOVER FEATURE
$(document).ready(function(){
    var firstHover=false;
    $(".detail-box .left .thumb-gall a").hover(function(){
        if(!firstHover){        
            firstHover = true;
            $(".detail-box .left div a.lightbox:first").unbind("click").click(function(){
                $(".detail-box .left .thumb-gall dd:eq("+$(this).attr("rel")+") a").click();
                return false;
            });            
            $(".detail-box .left").prepend('<a class="lightbox" href="'+$(".detail-box .left div a.lightbox:first").attr("href")+'"></a>');
            $(".lightbox").not(":eq(1)").lightBox();
        }
        $(".detail-box .left div a.lightbox:first img:last").attr("src", $(this).attr("rel") );
        $(".detail-box .left div a.lightbox:first").attr("href", $(this).attr("href") ).attr("rel", $(this).parents("dd:first").prevAll("dd").length);
    });
});

//GOOGLE MAP
$(document).ready(function() {
    if ($("#google-map").html()!=null){
        DGoogleMap2.setOption( 'zoom', 14 );
        DGoogleMap2.setOption( 'center', new GLatLng(44.5, 16.2) );
        DGoogleMap2.mapDefaultUI.zoom.scrollwheel=false;
        var s = DGoogleMap2.displayMap("#google-map");
        DGoogleMap2.displayMarkers();
        DGoogleMap2.fitMapToMarkers();
    }
    if ($(".mapBoxWrapper").html()!=null){
        var mapOffset = $(".mapBoxWrapper").offset();
        $("body").append('<div class="mapBox" style="top:'+mapOffset.top+'px; left:'+mapOffset.left+'px;"><a class="button">'+phrasebook.enlarge_map+'</a><strong class="title">'+phrasebook.show_on_map+'</strong><div id="gMap"></div></div>');
        $(window).resize(function(){
            mapOffset = $(".mapBoxWrapper").offset();
            $(".mapBox").css({left: mapOffset.left, top: mapOffset.top});
        });
        var markerCord = $(".mapBoxWrapper").attr("rel").split("|");
        DGoogleMap2.mapDefaultUI.zoom.scrollwheel=false;
        DGoogleMap2.setOption( 'center', new GLatLng(markerCord[0], markerCord[1]) );
        DGoogleMap2.mapObject = new GMap2( $( "#gMap" ).get(0) );
        DGoogleMap2.setCallback( 'displayMap', function() { setTimeout( "$( DGoogleMap2.mapObject.getContainer() ).children().each(function(){if( $(this).attr('id') && !DGoogleMap2.mapContainerFixedChildren[$(this).attr('id')] ) $(this).hide();});", 1000); } );
        DGoogleMap2.displayMap("#gMap");
        DGoogleMap2.setMarker( { 'lat':markerCord[0], 'lng':markerCord[1] }, false );
        $(".mapBox a.button").toggle(function(){
            var el = $(this);
            $(".mapBox").animate({width: "637px", height: "403px" },function(){
                el.addClass("close");
                DGoogleMap2.mapObject.checkResize();
                DGoogleMap2.fitMapToMarkers();
                DGoogleMap2.showMapControls();
                $(".mapBox .button").text(phrasebook.reduce_map);
            });
        },function(){
            var el = $(this);
            $(".mapBox").animate({width: "222px", height: "163px" }, function(){
                el.removeClass("close");
                DGoogleMap2.mapObject.checkResize();
                DGoogleMap2.fitMapToMarkers();               
                DGoogleMap2.hideMapControls();              
                $(".mapBox .button").text(phrasebook.enlarge_map);
            });
        });
    }
});

//CONTACT FORM
$(document).ready(function() {
    $("#contact-form").submit(function(){
        $("#contact-form .error").removeClass("error");
        $(this).find("label:has(em)").each(function(){
            if($(this).next().val()==""){ $(this).next().addClass("error"); }
        });
        if($("#contact-form .error").length!=0){ return false; }
    });
});

//FORM BOX POPUP
$(document).ready(function() {
    $('.top-nav .formPopup a').click(function(event){
      if($(this).attr("href")==undefined){
          $.get($(this).attr("rel"), function(data){
              $("body").append('<div id="formBox-overlay"></div><div id="formBoxContent">'+data+'</div>');          
              
              var overlayEl = $("#formBox-overlay");
              var popupEl = $("#formBoxContent");
              var closeButton = popupEl.find("form div img");          
              var left = ($(window).width() - popupEl.width())/2;
              var top = $(window).scrollTop()+50;
              
              $(window).resize(function(){ position_popup(overlayEl,popupEl); });
              overlayEl.click(function(){ close_popup(overlayEl,popupEl); });
              closeButton.click(function(){ close_popup(overlayEl,popupEl); });
              
              overlayEl.css({ height:$(document).height(), width:$(window).width(), opacity: "0.8" }).show();
              if((top+parseFloat(popupEl.height()))>overlayEl.height()){ overlayEl.height((top+parseFloat(popupEl.height()))+30); }
              popupEl.css({ left: left, top: top }).fadeIn("slow");
              
              $("#formBoxContent .forgotPass").click(function(){
                  $("#loginForm").slideUp();
                  $("#forgotForm").slideDown();
              });
              
              var validLoginForm=false;
              $("#loginForm").submit(function(){
                  if(validLoginForm==false){
                      $(this).find(".error").removeClass("error");
                      $(this).find("input.txt").each(function(){
                          if($(this).val()==""){ $(this).addClass("error"); }
                      });              
                      if($(this).find(".error").length!=0){ return false; }
                      else{
                          var loginForm_name = $("#loginForm #username").attr("value");
        	                var loginForm_pass = $("#loginForm #password").attr("value");
                          $.post(phrasebook.URL_ROOT+"/index.php?page=checkusers", { username: loginForm_name, password: loginForm_pass }, function(data){
                              if ( data == "true") {
                              	 validLoginForm=true;
                                 $("#loginForm").submit();
                              } else  {
                              	 alert("Upisali ste pogrešnu lozinku ili password!");
                              }
                          });
                          return false;
                      }
                  }
              });
              
              $("#forgotForm").submit(function(){
                      $(this).find(".error").removeClass("error");
                      $(this).find("input.txt").each(function(){
                          if($(this).val()==""){ $(this).addClass("error"); }
                      });              
                      if($(this).find(".error").length!=0){ return false; }
                      else{
        	                var forgotForm_email = $("#forgotForm #email").attr("value");
                          $.post($(this).attr("action"), { email: forgotForm_email }, function(data){
                              if ( data == "true") {
                                  alert("Na vašu e-mail adresu je poslano korisničko ime i lozinka!");
                                  $("#loginForm").slideDown();
                                  $("#forgotForm").slideUp();
                              } else  {
                                  alert("Upisali ste e-mail adresu koja se ne postoji u našoj bazi!");
                              }
                          });
                          return false;
                      }
    
              });
              
          });
      }
	});
});

function position_popup(overlayEl,popupEl){
    overlayEl.hide().css({ height:$(document).height(), width:$(document).width(), opacity: "0.8" }).show();
    var left = ($(window).width() - popupEl.width())/2;
    var top = $(window).scrollTop()+50;
    popupEl.css({ left: left, top: top });
}

function close_popup(overlayEl,popupEl){      
    popupEl.fadeOut("slow",function(){
        popupEl.remove();
        jsPopup_Amount=0;
    });
    overlayEl.fadeOut("slow",function(){
        $("select").css("visibility","visible");        
        overlayEl.remove();
    });
    $(window).unbind("resize");
    $("body").removeClass("printPopup");
}


//QUERY POPUP
$(document).ready(function() {
    $('.text ul .button a:first').click(function(event){
	    var re_realEstates_id = $(this).attr("rel");
      $.get(phrasebook.URL_ROOT+"/index.php?page=queryPopup&re_realEstates_id="+re_realEstates_id, function(data){
          $("body").append(data);          
          var pos = $("#column-1").position();
          $("#queryPopup").css({ top: pos.top+150, left: pos.left+150 }).show();
          
          $(window).resize(function(){
              var pos = $("#column-1").position();
              $("#queryPopup").css({ top: pos.top, left: pos.left }).show();
          });          
          
          $("#queryPopup .close").click(function(){
              $("#queryPopup").remove();
          });
          
          $(document).bind('click', function(e){
              var $clicked = $(e.target);
              if (!($clicked.is('#queryPopup') || $clicked.parents().is('#queryPopup'))) {
                $("#queryPopup").remove();
                $(document).unbind('click');
              }
          });  
          var realEstateAction = $("#queryPopup form").attr("action");
          $("#queryPopup button[type=submit]").click(function(){
              $("#queryPopup input").removeClass("error");
              switch ($("#queryPopup .radio:checked").val()){
                  case "email":
                    if( $("#quaryEmail").val()=="" ){ $("#quaryEmail").addClass("error"); }                   
                    break;
                  case "phone":
                    if( $("#quaryPhone").val()=="" ){ $("#quaryPhone").addClass("error"); }
                    break;              
              }
              if($("#queryPopup .error").length>0){ return false; }
              else {
                  $.get(realEstateAction, { re_realEstates_id:$("#re_realEstates_id").val(),re_realEstates_title:$("#re_realEstates_title").val(),contact_method:"email",quaryName:$("#quaryName").val(),quaryPhone:$("#quaryPhone").val(),quaryEmail:$("#quaryEmail").val(),quaryMessage:$("#quaryMessage").val() },function(data){
                    $("#queryPopup fieldset.left").remove();
                    $("#queryPopup fieldset label").remove();
                    $("#queryPopup fieldset textarea").remove();
                    $("#queryPopup button[type=submit]").remove();
                    $("#queryPopup blockquote").after("<p class='note'>"+data+"</p>");
                    
                	});
              }
              return false;
          });
      });
	});
});

//OPEN VIDEO
$(document).ready(function() {
    $(".files .video a").click(function(){
        $("select").css("visibility","hidden");
        $("body").append('<div id="video-popup-overlay" title="zatvori"></div><div id="video-popup"><div id="flashVideoPopup"></div><img class="close" src="'+phrasebook.URL_ROOT+'/images/lightbox-btn-close.gif" alt="zatvori" title="zatvori" /></div>');
        
        var overlayEl = $("#video-popup-overlay");
        var popupEl = $("#video-popup");
        var closeButton = popupEl.find(".close");          
        var left = ($(window).width() - popupEl.width())/2;
        var top = $(window).scrollTop()+50;
        
        $(window).resize(function(){ position_popup(overlayEl,popupEl); });
        overlayEl.click(function(){ close_popup(overlayEl,popupEl); });
        closeButton.click(function(){ close_popup(overlayEl,popupEl); });

        var link=$(this).attr("rel");
        var timestamp = Number(new Date());
        var flashvars = {file: link,controlbar: "over",autostart: "true"};
        var params = {allowscriptaccess: "always",allowfullscreen: "true"};
        var attributes = {id: "mpl",name: "mpl"};
        swfobject.embedSWF(phrasebook.URL_ROOT+'/player.swf?'+timestamp, "flashVideoPopup", "480", "384", "9","", flashvars, params, attributes);

        overlayEl.css({ height:$(document).height(), width:$(window).width(), opacity: "0.8" }).show();
        if((top+parseFloat(popupEl.height()))>overlayEl.height()){ overlayEl.height((top+parseFloat(popupEl.height()))+30); }
        popupEl.css({ left: left, top: top }).fadeIn("slow");        
    });
    function position_popup(overlayEl,popupEl){
        overlayEl.hide().css({ height:$(document).height(), width:$(document).width(), opacity: "0.8" }).show();
        var left = ($(window).width() - popupEl.width())/2;
        var top = $(window).scrollTop()+50;
        popupEl.css({ left: left, top: top });
    }
    function close_popup(overlayEl,popupEl){
        playerPopupVideo = null;
        swfobject.removeSWF("mpl");
       
        popupEl.fadeOut("slow",function(){
            popupEl.remove();
        });
        overlayEl.fadeOut("slow",function(){
            $("select").css("visibility","visible");        
            overlayEl.remove();
        });
        $(window).unbind("resize");
    }
});

//FLASH POPUP FOR VIRTUAL WALK
$(function()
{
	$('#flash-popup-overlay').hide();
	$('#flash-popup').hide();
	$('.flash-popup-link').click(function(e)
	{
		e.preventDefault();
		var windowWidth = document.documentElement.scrollWidth;
		var windowHeight = document.documentElement.scrollHeight;
		var popupHeight = $('#flash-popup').height();
		var popupWidth = $('#flash-popup').width();
		var viewHeight = $(document).scrollTop() + (popupHeight/2);
		var fromTop = $(this).offset();
		//centering
		$('#flash-popup').css({
			'position': 'absolute',
			'top': viewHeight,//fromTop.top,
			'left': windowWidth/2-popupWidth/2
		});
		
		//overlay size
		$('#flash-popup-overlay').css({
			'height': windowHeight,
			'width': windowWidth
		});
		
		var popupx = $('#flash-popup').css('top');
		var popupy = $('#flash-popup').css('left');
		

		//show all
		$('#flash-popup-overlay').animate({opacity:0}, '1').fadeIn().animate({opacity:0.6}, '2000').append('<a id="flash-popup-close" href="#"></a>');
		$('#flash-popup-close').show();
		$('#flash-popup').show();
		$('#flash-popup').html( unescapeHtml( $(this).next('div.virtual-walk-code').html() ) );
		
		//close btn position
		$('#flash-popup-close').css({
			'top': parseInt(popupx) - 15 + 'px',
			'left': parseInt(popupy) + parseInt(popupWidth) + 10 + 'px'
		});
		
		
		//close
		$('#flash-popup-overlay').click(function()
		{
			$('#flash-popup-overlay').fadeOut('fast');
			$('#flash-popup').fadeOut('slow');
		});
		$('#flash-popup-close').click(function(e)
		{
			e.preventDefault();
			$('#flash-popup-overlay').fadeOut('fast');
			$('#flash-popup').fadeOut('slow');
		});
	});
});

function unescapeHtml(unsafe) {
  return unsafe
      .replace(/&amp;/g, "&")
      .replace(/&lt;/g, "<")
      .replace(/&gt;/g, ">")
      .replace(/&quot;/g, '"')
      .replace(/&#039;/g, "'");
}



//TICKER
$(document).ready(function(){

	var textWidth = $('#sub-header .down span').width() / 2 -50;
	function ticker(){
		$('#sub-header .down span').animate({
			left: '-='+textWidth
		}, 12000, 'linear', function() {
			$(this).css({'top':'0', 'left':'10px'})
			ticker();
		});
	}
	ticker();
});





