var itemAnimEnabled = true;
//lavaItem is set in any page of navigation menu accordingly (server-side)
var lavaItem = 0;
$(document).ready(function() {
if(lavaItem == -1)
	$('#lavaLampNav').lavaLamp({fx: 'swing', speed: 333, returnHome:true, homeLeft: 800, homeTop: 0, homeWidth:70, homeHeight:20});
else
	$('#lavaLampNav').lavaLamp({fx: 'swing', speed: 333, startItem:lavaItem});
$().ready(function() {

	//Coda Slider Tabs (aka RSSTabs)
	$('#coda-slider-1').codaSlider({dynamicArrows:false, dynamicTabs: false, firstPanelToLoad: 1});});
	$('#getLink').css('display', 'block');
	//Auto Suggestion
	$('.sw_qbox').keyup(function(){
		lookup($('.sw_qbox').val());
	});
	$('.sw_qbox').blur(function(){
	setTimeout("$('#suggestions').hide();", 200);
		//fill();
	}); 

	//Page Init procedure
    $('.sw_qbox').val('');
    var qboxval = document.getElementById("qbox").value;
    if (qboxval != '')
        $(".sw_qbox").val(qboxval);
    checkSearchBox();

    $('#catVal').html("فعالیت");
    $('#regVal').html("محدوده");

    //var oddsColor = "#01B8FE";
    //$(".item:odd").addClass("odd");

    $('.selectedSubItem').parent().show().parent().addClass("openItem").addClass("subCatPreOpened");
    $('.selectedItem').children(".subCats").show();

    $('.catItem').not(".selectedItem").click(function(event) {
        var isOpen = $(this).hasClass("openItem");
        $(".openItem").removeClass("openItem").children().filter(".subCats").slideToggle('slow');
        if (!isOpen) {
            $(this).addClass("openItem");
            $(this).children().filter(".subCats").slideToggle('slow');
        }
    });
    //Search form submit
    $('#searchForm').submit(function() {
  		if($('.sw_qbox').hasClass('blur'))
  		{
  			$(".sw_qbox").val('');
  		}
	});

    
    //Fix jump bug
    /*$(".subCatItem").not(".selectedSubItem").hover(
        function() { $(this).children("A").css({ color: "#000" }); },
        function() { $(this).children("A").css({ color: "#fff" }); });*/
    $(".subCatItem").click(
        function(e) {
            e.stopPropagation();
            window.location = $(this).children("a").attr("href");
        });

    $(".headerLinks").hover(function() {
        $(this).animate({ height: "20px" }, 200);
    }, function() { $(this).animate({ height: "14px" }, 300); });

    var navDuration = 150; //time in miliseconds
    var navJumpHeight = "0.45em";

    //Header Menu
    /*$('.headerMenu li').hover(function() {
        $(this).animate({ height: "20", backgroundColor: "#00B3DF" }, navDuration);
    }, function() {
        $(this).animate({ height: "14px", backgroundColor: "#32393D" }, navDuration * 1.5);
    });*/

    //SearchBox
    var isInFocus = false;

    $(".sw_qbox").focus(function() {
        if ($(this).hasClass('blur')) {
            $(this).val('');
            $(this).removeClass('blur');
            isInFocus = true;
        }
    });

    $(".sw_qbox").blur(function() {
        isInFocus = false;
        $("#qbox").val($(this).val());
        checkSearchBox();
    });

    $("#searchForm").submit(function() {
        if (isInFocus)
            $("#qbox").val($("#sw_qbox").val());
    });

    //Search options
    $(".searchSelector").children().click(function(e) {
        switch (e.target.className) {
            case "picOption":
                $("#modeField").val("1");
                $(this).removeClass("unselectedOption");
                $(this).addClass("selectedOption");
                $("#textOption").removeClass("selectedOption");
                $("#textOption").addClass("unselectedOption");
                break;
            case "txtOption":
                $("#modeField").val("2");
                $(this).removeClass("unselectedOption");
                $(this).addClass("selectedOption");
                $("#picsOption").removeClass("selectedOption");
                $("#picsOption").addClass("unselectedOption");
                if (!$.browser.msie) {
                    $(this).css({ marginTop: "-0.5px" });
                }
                break;
        }
    });

    //Item's hover action
    var itemJumpHeight = "15px";
    var origColor;
    $('.item').hover(function() {
        if ($(this).hasClass("featuredItem"))
            $(this).addClass("featuredItemHover");
        else
            $(this).addClass("hoveredItem");

        if (itemAnimEnabled) {
            $(this).animate({ marginTop: "-=" + itemJumpHeight
            }, 200);
            if (jQuery.browser.version.substr(0, 3) == "6.0")
                $(this).parent().css({ borderTop: "1px #83bc46 solid" });
        }
    }, function() {
        if (itemAnimEnabled) {
            if (jQuery.browser.version.substr(0, 3) == "6.0")
                $(this).parent().css({ borderTop: "1px #999999 solid" });
            $(this).animate({ marginTop: "0px" }, 300, null, function() {
                if (jQuery.browser.version.substr(0, 3) == "6.0")
                    $(this).parent().css({ borderTop: "1px #fff solid" });
            });
        }

        if ($(this).hasClass("featuredItem"))
            $(this).removeClass("featuredItemHover");
        else
            $(this).removeClass("hoveredItem");
    });

    $('.item').click(function() {
        //poptastic($(this).children(".title").children(".outer").children(".middle").children(".inner").children("a").attr("href"));
        poptastic($(this).children(".title").children(".titleMid").children("a").attr("href"));
    });

    //Filter Menus
    //Categories Filter Menu
    $('.catMenu li').click(function() {
        if (!$(this).hasClass('active')) {
            $('.catMenu .active').removeClass('active');
            $(this).addClass('active');
        } else
            $(this).removeClass('active');

    });
    //Regions Filter Menu
    $('.regMenu li').click(function() {
        if (!$(this).hasClass('active'))
            $(this).addClass('active');
        else
            $(this).removeClass('active');
    });

});

function CommitFiltersValues() {
	$('#categoryBox').addClass('selectionBoxAltered');
	$('#regionBox').addClass('selectionBoxAltered');
	
    //Clear Everything
    //$('#catVal').html("");
    //$('#regVal').html("");
    $('#regField').val('');
    $('#catField').val('');

    //Categories Value
    //$('#catVal').html($('.catMenu .active').html());

    var i = 0;
    var MAXRegs = 15;
    //Regions Values
    $('.regMenu .active .num').each(function() {
        /*if (i < MAXRegs) {
            $('#regVal').html($('#regVal').html() + ", " + $(this).html());
            i++;
        }*/
        $('#regField').val($('#regField').val() + "," + $(this).next().html());
    });
    //remove the last ', '
    /*if (i < MAXRegs)
        $('#regVal').html($('#regVal').html().replace(', ', ''));
    else {
        $('#regVal').html($('#regVal').html().replace(', ', ''));
        $('#regVal').html($('#regVal').html() + ",...");
    }*/

    $('#regField').val($('#regField').val().replace(',', ''));
    $('#catField').val($('.catMenu .active').children(".hidden").html());
    //alert($('#regField').val());
    //alert($('#catField').val());

    //Check if nothing's selected
    if (jQuery.trim($('#catVal').html()) == "")
		$('#categoryBox').removeClass('selectionBoxAltered');
    if (jQuery.trim($('#regVal').html()) == "" || $('.regMenu .active').size() == $('.regMenu li').size())
        $('#regionBox').removeClass('selectionBoxAltered');
    
}

function checkSearchBox() {
    var predefined_txt = "جستجو نام یا گروه آگهی";
    if ($.trim($('.sw_qbox').val()) == '') {
        $('.sw_qbox').val(predefined_txt);
        $('.sw_qbox').addClass('blur');
    }
}

var newwindow;
function poptastic(url) {
    newwindow = window.open(url, '_blank', 'height=700,width=900,resizable=no');
    if (window.focus) { newwindow.focus() }
}

function lookup(inputString) {
		if(inputString.length == 0) {
			// Hide the suggestion box.
			$('#suggestions').hide();
		} else {
			$.post("/api/suggest", {keyword: inputString}, function(data){
				if(data.length >0) {
					$('#suggestions').show();
					$('#autoSuggestionsList').html("");
					$.each(data, function(i, item){
					$('#autoSuggestionsList').append(
						"<li onclick=\"fill('"+item+"')\">"+item+"</li>");
						});
				}
			}, "json");
		}
	} // lookup
	
	function fill(thisValue) {
		$('.sw_qbox').val(thisValue);
		setTimeout("$('#suggestions').hide();", 200);
		$('#searchForm').submit();
	}
function keyenter(field,e)
{
var key;
if (window.event)
   key = window.event.keyCode;
if (key>31)
  if (key<128)
  {
    if (window.event)
      window.event.keyCode=' !"#$%،گ)(×+و-./0123456789:ك,=.؟@ِذ}ىُيلا÷ـ،/’د×؛َءٍف‘{ًْإ~جژچ^_پشذزيثبلاهتنمئدخحضقسفعرصطغظ<|>ّ'.charCodeAt(key-32);
  }
}