$(document).ready(function(){
    makeToolTips();

	$("#categories").treeview({
		animated: "fast",
		unique: true,
		control: "#treecontrol",
		collapsed: true
	});
	
	recalculateInput = function(){
	   $('#holderul .bit-box').each(function(intIndex, objValue){
	       var checkboxId = $(objValue).attr('rel');
	       var state = $('#categories [value="'+checkboxId+'"]').attr('checked')
	       if(state == false)
	       {
	           $("#cb_"+checkboxId).click();
	       }
	   });
	}
	
	changeCheckBoxStatus = function(sId, iStatus, blNotRecalculate){
		// iStatus: 1 - checked, 2 - checked+disabled, 3 - unchecked
		sImgId = 'img-'+sId;

		if (iStatus == 1)
		{
			$("#"+sImgId).attr('class', 'imgcheckboxselected');
			$("#"+sId).attr('checked', 'checked');
			$("#"+sId).removeAttr('disabled');
			
			/*
			var value = $("#"+sId).val();
			if(typeof(value) != "undefined" && value.match("^roundtrip"))
			{
			     $('[name=search\\[duration_from\\]]').val('');
			     $('[name=search\\[duration_to\\]]').val('');
			}
			*/
		}
		else if(iStatus == 2)
		{
			$("#"+sImgId).attr('class', 'imgcheckboxdisabled');
			$("#"+sId).attr('checked', 'checked');
			$("#"+sId).attr('disabled', 'disabled');
		}
		else
		{
			$("#"+sImgId).attr('class', 'imgcheckbox');
			$("#"+sId).removeAttr('checked');
			$("#"+sId).removeAttr('disabled');
		}

		if (!blNotRecalculate)
		{
			calculateCheckboxes($("#"+sId));
		}
	}

	$(".imgcheckbox").live("click", function(){

		aParts = $(this).attr("id").split('-');
		aParts = aParts.slice(1, aParts.length);
		sClickId = aParts.join('-', aParts);

		changeCheckBoxStatus(sClickId, 1);
		
		recalculateInput();
	});
	
	$(".imgcheckboxselected").live("click", function(){
		
		aParts = $(this).attr("id").split('-');
		aParts = aParts.slice(1, aParts.length);
		sClickId = aParts.join('-', aParts);

		
		// remove from search input:
		sItemId = $("#"+sClickId).val();
		if (sItemId)
		{
			oItem = $("#holderul [rel='"+sItemId+"']").find("a.closebutton").click();
		}
		
		changeCheckBoxStatus(sClickId, 3);
		
		recalculateInput();
	});	
	
	$(".imgcheckboxdisabled").live("click", function(){
		
		aParts = $(this).attr("id").split('-');
		aParts = aParts.slice(1, aParts.length);
		sClickId = aParts.join('-', aParts);

		changeCheckBoxStatus(sClickId, 1);
		
		recalculateInput();
	});	
	
	calculateCheckboxes = function(item)	{
		
		sSelectedId = $(item).attr('id');
		blState = $(item).is(":checked");
		
		// checking all childs:
		if (blState)	{	$("[id^='"+sSelectedId+"-']").each(	function(intIndex, objValue){	changeCheckBoxStatus($(objValue).attr('id'), 1, true);	});}
		// unchecking all childs:
		else{	$("[id^='"+sSelectedId+"-']").each(	function(intIndex, objValue){	changeCheckBoxStatus($(objValue).attr('id'), 3, true);	});	}
		
		// working with parents:
		if(typeof(sSelectedId) != 'undefined')
		{
    		aParts = sSelectedId.split('-');
    		aParts = aParts.slice(0, aParts.length-1);
    
    		// clicked on child:
    		if (aParts.length > 1)
    		{
    			// level id:
    			aTmp = $(item).attr('class').split(' ');
    			sLevelClassId = aTmp[aTmp.length-1];
    			
    			calculateParentCheckboxes(sLevelClassId, aParts);
    		}
		}
	}

	calculateParentCheckboxes = function(sLevelClassId, aParts)	{

		sLevelId = aParts.join('-', aParts);
		iBranches = 0;
		iSelectedBranches = 0;
		
		$("[id^='"+sLevelId+"-']").each(	
			function(intIndex, objValue){
				
				if ($(objValue).hasClass(sLevelClassId))
				{
					iBranches = iBranches + 1;

					// same level:
					if ($(objValue).is(":disabled"))
					{
						iSelectedBranches = iSelectedBranches + 0.5;
					}
					else if ($(objValue).is(":checked"))
					{
						iSelectedBranches = iSelectedBranches + 1;
					}
				}
			}
		);

		aParts = aParts.slice(0, aParts.length-1);
		sLevelUp = aParts.join('-', aParts);
		
		// if not all selected:
		if (iSelectedBranches > 0)
		{
			if (iBranches > iSelectedBranches)
			{
				changeCheckBoxStatus(sLevelId, 2, true);
			}
			else
			{
				changeCheckBoxStatus(sLevelId, 1, true);
			}
		}
		else
		{
			changeCheckBoxStatus(sLevelId, 3, true);
		}

		// going up:
		if (aParts.length > 0)
		{
			// level id:
			aTmp = $("[id='"+sLevelId+"']:last").attr('class').split(' ');
			sLevelClassId = aTmp[aTmp.length-1];
			calculateParentCheckboxes(sLevelClassId, aParts);
		}
	}	
	
	$("#categories").mouseleave(function(){
    	treecontrolcms = setTimeout(function(){
			clearTimeout(treecontrolcms);
			$('#treecontrolc').click()
		}, 2000);
    });
    
	$("#categories").mouseenter(function(){
		try	{
			clearTimeout(treecontrolcms);
		}
		catch(err)	{
		}
    });
	 
    $(".external").attr("target", "_blank");
    
    $("a.expand,a.collapse").live("click", function(){
    	if($(this).hasClass("expand")){
			$(this).removeClass("expand").addClass("collapse").parent().find("table").show();
		}else{
			$(this).removeClass("collapse").addClass("expand").parent().find("table").hide();
		}
    });
    
	$('.date-pick').datepicker({dateFormat: 'yy-mm-dd','minDate': 0});
      
     $("#search_childs").click(function(){
        iSelected = $(this).val();
        if (iSelected>0)
        {
            $("#childSelectBlock").show();
            for( i=0; i < 3; i++)
            {
                if (i<iSelected)
                    $("#search_childs_age_"+i).show();
                else
                    $("#search_childs_age_"+i).hide();
            }
        }
        else
        {
            $("#childSelectBlock").hide();
            for( i=0; i < 3; i++)
            {
                $("#search_childs_age_"+i).hide();
            }
        }
     });
     
     $("#maininput_title").live("click", function(){
    	 $("#maininput_title").hide();
     });
     $(".maininput").live("click", function(){
    	 $("#maininput_title").hide();
     });
 	
 	$("#hotelfilterlink").click(function(){
 		if ($(".hotelfilter").is(":hidden"))
 		{
 			$(".hotelfilter").show();
 		}
 		else
 		{
 			$(".hotelfilter").hide();
 		}
 		updateIframeHeight();
 	});
 	
 	selectTravelId = function(sTravelId){
 		$("#priceId"+sTravelId).attr('checked', 'checked');
 		updateSummary(sTravelId);
 		
 		setTimeout("document.location = '#travel_summary';", 500);
 	}
 	
 	start2checkout = function(sTravelId){
 		$("#mtravelid").val(sTravelId);
 		$("#start2checkoutform").submit();
 	}
 	
 	// travel info tabs
    $('.travelInfoTabContent').hide();
    $('.tab1').show();
    $('#tab1').addClass('step2-travel-tab-selected');
    $('.step2-travel-tab').click(function(){
        var id = $(this).attr('id');
        
        $('.travelInfoTabContent').hide();
        $('.'+id).show();
        
        $('#tab1').removeClass('step2-travel-tab-selected');
        $('#tab2').removeClass('step2-travel-tab-selected');
        $('#tab3').removeClass('step2-travel-tab-selected');
        $('#tab4').removeClass('step2-travel-tab-selected');
        $(this).addClass('step2-travel-tab-selected');
        
        updateIframeHeight();
    });

});      
showAllTravelOffers = function(destination) {
    $("#date_f").val('');

    $("#categories input[name='search[travel_type][]']").each(function() {
        
        if($(this).val() == destination) {
            changeCheckBoxStatus($(this).attr("id"),1, false);
        }else{
            changeCheckBoxStatus($(this).attr("id"),3, false);
        }
    });
    $('#filter').submit();
    return false;
}


 var sfOnFcbkSelectOption = function(item) {
	 changeCheckBoxStatus($("#categories input[value='"+ item._value +"']").attr("id"), 1);
 }    
 var sfOnFcbkRemoveOption = function(item) {
	 changeCheckBoxStatus($("#categories input[value='"+ item._value +"']").attr("id"), 3);
 }
 
 var getPage = function(thePage,wt,ht)   { 
     if(wt=="")wt=300;
     if(ht=="")wt=300;
     leftPos= (screen.width-wt)/2 
     topPos = (screen.height-ht)/2
     rnd = Math.round(1000*Math.random());
     newWin1 = window.open(thePage,'popup'+rnd,'toolbars=no,resizable=yes,scrollbars=yes,left='+leftPos+',top='+topPos+',width='+wt+',height='+ht) 
 }
 
function makeToolTips($id){
    if ($.browser.msie && $.browser.version == '6.0' ) return;
    if(!$id) $id = '[class$="tooltip"][title!=""]';
    $($id).qtip({
        style: {    
            border: { width: 1, radius: 2, color: '#FEE2A4' },
            background: '#FFF',
            tip: true
        },
        show: { delay:300   }
    });
}
 
