//if(!console) var console = {log: function(msg) { return; }};
var searchTimer = null;

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString())+ "; path=/";
}
 
function getCookie(c_name, defvalue){
if (document.cookie.length>0){
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1){ 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
	return defvalue;
}

function selectInfoWindow(scope) {
    var id = $(scope).attr("rel");
    if(id) {
        $(".infowindow").hide();
        $("#"+id).show();
    } else {
        id = $($(scope).parents(".option")[0]).attr("rel");
        if(id) {
            $(".infowindow").hide();
            $("#"+id).show();
        }
    }
}

function updateResultList(openFirst) {
    $("#search_results_list > li").each(function() {
        $(".small",this).toggle();
        $(".full",this).toggle();
    });
    $("#search_results_list > li").mousedown(function(e) {
        $(".small",this).toggle();
        $(".full",this).toggle();
    });
    $('.changeshortlong').click(function() {
        var parent = $(this).parent();
        $(".short", parent).toggle("slow");
        $(".long", parent).toggle("slow")
    });
    $(".change_page").click(function(e) {
        e.preventDefault();
        setPage($(this).attr("rel"));
        $("#spinner").show();
        $.scrollTo($("#results"),100);
        if($(this).hasClass("openfirst")){ 
            ajaxSearch(true);
        }else
            ajaxSearch();
    });
    location.href = "#?"+$("#search_form").serialize();
    if(openFirst) $(".changeshortlong").first().click();
}

function openPrev(scope){
    var parent = $(scope).parents(".infoitem");
    $.scrollTo($(parent).prev(),300);
    $(".short", $(parent).prev()).click();
}

function openNext(scope){
    var parent = $(scope).parents(".infoitem");
    $.scrollTo(parent,300);
    $(".short", $(parent).next()).click();

}

function setPage(page) {
    $("#id_page").val(page);
}

var refreshTime = 500;
function queueSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(function () { ajaxSearch()},refreshTime);
}
var lastHREF = "";
var historyTimeout = null;
function queryUpdateFromHistory() {
    if (historyTimeout) clearTimeout(historyTimeout);
    historyTimeout = setTimeout(function() { updateFromHistory();}, 100);
}

function updateFromHistory() {
    console.log("Checking");
    if( location.href == lastHREF ) return;
    lastHREF = location.href;
    var def_page = $("page").val();
    var def_min_postal_code = $("min_postal_code").val();
    var def_max_postal_code = $("max_postal_code").val();
    var def_min_size = $("min_size").val();
    var def_max_size = $("max_size").val();
    var def_min_rooms = $("min_rooms").val();
    var def_max_rooms = $("max_rooms").val();
    var def_min_price = $("min_price").val();
    var def_max_price = $("max_price").val();

    var page = def_page;
    var min_postal_code = def_min_postal_code;
    var max_postal_code = def_max_postal_code
    var min_size = def_min_size;
    var max_size = def_max_size;
    var min_rooms = def_min_rooms;
    var max_rooms = def_max_rooms;
    var min_price = def_min_price;
    var max_price = def_max_price;

    var p = location.href.search("#");
    if ( p > 0 ) {
        var n = location.href.length;
        p++;
        var data  = location.href.substr(p, n-p);
        var efArray = data.split("?");
        var formData = false, openItems = false
        openItems = efArray[0].split(",");
        if(efArray.length > 1)
            formData = efArray[1].split("&");

        for(var i=0;i<openItems.length; i++) {
            // TODO: open items
        }

        for(var i=0;i<formData.length; i++) {
            var lst = formData[i].split("=");
            var item = lst[0];
            var value = lst[1];

            if(value != ""){
                if (item=="page") page = parseInt(value);
                if (item=="min_postal_code") min_postal_code = parseInt(value);
                if (item=="max_postal_code") max_postal_code = parseInt(value);
                if (item=="min_size") min_size = parseInt(value);
                if (item=="max_size") max_size = parseInt(value);
                if (item=="min_rooms") min_rooms = parseInt(value);
                if (item=="max_rooms") max_rooms = parseInt(value);
                if (item=="min_price") min_price = parseInt(value);
                if (item=="max_price") max_price = parseInt(value);
            }
        }
    }

    var ajaxUpdate = ! ( (def_min_postal_code == min_postal_code ) &&
                       (def_max_postal_code == max_postal_code ) &&
                       (def_min_size == min_size ) &&
                       (def_max_size == max_size ) &&
                       (def_min_rooms == min_rooms ) &&
                       (def_max_rooms == max_rooms ) &&
                       (def_min_price == min_price ) &&
                       (def_max_price == max_price ) );

    if( ajaxUpdate ) {
        console.log("Updating");
        $("#id_page").val( page );
        $("#id_min_postal_code").val( min_postal_code );
        $( "#postal-range" ).slider( "option", "min", min_postal_code );
        $("#id_max_postal_code").val( max_postal_code);
        $( "#postal-range" ).slider( "option", "max", max_postal_code );
        $("#id_min_size").val( min_size );
        $( "#size-range" ).slider( "option", "min", min_size );
        $("#id_max_size").val( max_size ); 
        $( "#size-range" ).slider( "option", "max", max_size );
        $("#id_min_rooms").val( min_rooms );
        $( "#rooms-range" ).slider( "option", "min", min_rooms );
        $("#id_max_rooms").val( max_rooms );
        $( "#rooms-range" ).slider( "option", "max", max_rooms );
        $("#id_min_price").val( min_price );
        $( "#price-range" ).slider( "option", "min", min_price );
        $("#id_max_price").val( max_price );
        $( "#price-range" ).slider( "option", "max", max_price );


        queueSearch();        
    } 
}
var paneChangeTimer; //  = new Array(100), currentChangeTimer = 0, clearedChangeTimer = 0;
var lastPaneButton;
$( document ).ready( function() {

    $.scrollTo(0);
    var def_page = 1;
    var def_min_postal_code = 0;
    var def_max_postal_code = 10000;
    var def_min_size = 25;
    var def_max_size = 220;
    var def_min_rooms = 0;
    var def_max_rooms = 10;
    var def_min_price = 0;
    var def_max_price = 10000;
    var def_postal_codes = "";

    var page = def_page;
    var min_postal_code = getCookie("min_postal_code", def_min_postal_code);
    var max_postal_code = getCookie("max_postal_code",def_max_postal_code);
    var min_size = getCookie("min_size",def_min_size);
    var max_size = getCookie("max_size",def_max_size);
    var min_rooms = getCookie("min_rooms",def_min_rooms);
    var max_rooms = getCookie("max_rooms",def_max_rooms);
    var min_price = getCookie("min_price",def_min_price);
    var max_price = getCookie("max_price",def_max_price);
    var postal_codes = getCookie("postal_codes",def_postal_codes).replace(/%2C/g,",").split(",");

    var p = location.href.search("#");
    if ( p > 0 ) {
        var n = location.href.length;
        p++;
        var data  = location.href.substr(p, n-p);
        var efArray = data.split("?");
        var formData = false, openItems = false
        openItems = efArray[0].split(",");
        if(efArray.length > 1)
            formData = efArray[1].split("&");

        for(var i=0;i<openItems.length; i++) {
            // TODO: open items
        }

        for(var i=0;i<formData.length; i++) {
            var lst = formData[i].split("=");
            var item = lst[0];
            var value = lst[1];

            if(value != ""){
                if (item=="page") page = parseInt(value);
                if (item=="postal_codes") postal_codes = value.replace(/%2C/g,",").split(",");
                if (item=="min_size") min_size = parseInt(value);
                if (item=="max_size") max_size = parseInt(value);
                if (item=="min_rooms") min_rooms = parseInt(value);
                if (item=="max_rooms") max_rooms = parseInt(value);
                if (item=="min_price") min_price = parseInt(value);
                if (item=="max_price") max_price = parseInt(value);
            }
        }
    }

    var ajaxUpdate = ! ( (def_min_postal_code == min_postal_code ) &&
                       (def_max_postal_code == max_postal_code ) &&
                       (def_min_size == min_size ) &&
                       (def_max_size == max_size ) &&
                       (def_min_rooms == min_rooms ) &&
                       (def_max_rooms == max_rooms ) &&
                       (def_min_price == min_price ) &&
                       (def_max_price == max_price ) );
    
    $( '#searchSubmit' ).click( function(e) {
        e.preventDefault();            
        ajaxSearch();
    });
    
    $( '.searchInput' ).change(function(e) {
        queueSearch();
    });
    $( '.searchInput' ).keydown(function(e) {
        queueSearch();
    });
    $( '#spinner' ).hide();

    /* Updating postal codes */
    for(n in postal_codes) {
       post = postal_codes[n];
       var reg =0;
        for(var i=1;i<=14;i++) {
           if(regions[i]['postals'][post]) reg = i;
        }
        postalCodes[post] = reg;
    }
    updateRegionList(true);

    /* Updating search texts */
    $( "#id_min_price" ).val(min_price);
    $( "#id_max_price" ).val(max_price);
    $( "#id_label_min_price" ).text(convertCurrency(min_price));
    $( "#id_label_max_price" ).text(convertCurrency(max_price));


    $( "#id_min_size" ).val(min_size);
    $( "#id_max_size" ).val(max_size);
    $( "#id_label_min_size" ).text(min_size);
    $( "#id_label_max_size" ).text(max_size);

    $( "#id_min_rooms" ).val(min_rooms);
    $( "#id_max_rooms" ).val(max_rooms);
    $( "#id_label_min_rooms" ).text(min_rooms);
    $( "#id_label_max_rooms" ).text(max_rooms);

    
    $( "#price-range" ).slider({
	range: true,
	min: 0,
        step:500,
	max: 30000,
	values: [ min_price, max_price ],
	slide: function( event, ui ) {
            selectInfoWindow(this);
            setPage(1);
	    $( "#id_min_price" ).val(ui.values[ 0 ]);
	    $( "#id_max_price" ).val(ui.values[ 1 ]);
	    $( "#id_label_min_price" ).text(convertCurrency(ui.values[ 0 ]));
	    $( "#id_label_max_price" ).text(convertCurrency(ui.values[ 1 ]));
            setCookie("min_price", ui.values[ 0 ]);
            setCookie("max_price", ui.values[ 1 ]);
            queueSearch();
	}
    });
    
    
    $( "#size-range" ).slider({
	range: true,
	min: 0,
        step:5,
	max: 300,
	values: [ min_size, max_size ],
	slide: function( event, ui ) {
            selectInfoWindow(this);
            setPage(1);
	    $( "#id_min_size" ).val(ui.values[ 0 ]);
	    $( "#id_max_size" ).val(ui.values[ 1 ]);
	    $( "#id_label_min_size" ).text(ui.values[ 0 ]);
	    $( "#id_label_max_size" ).text(ui.values[ 1 ]);
            setCookie("min_size", ui.values[ 0 ]);
            setCookie("max_size", ui.values[ 1 ]);
            queueSearch();
	}
    });
    
    
    $( "#rooms-range" ).slider({
	range: true,
	min: 0,
        step:1,
	max: 15,
	values: [ min_rooms, max_rooms ],
	slide: function( event, ui ) {
            selectInfoWindow(this);
            setPage(1);
	    $( "#id_min_rooms" ).val(ui.values[ 0 ]);
	    $( "#id_max_rooms" ).val(ui.values[ 1 ]);
	    $( "#id_label_min_rooms" ).text(ui.values[ 0 ]);
	    $( "#id_label_max_rooms" ).text(ui.values[ 1 ]);
            setCookie("min_rooms", ui.values[ 0 ]);
            setCookie("max_rooms", ui.values[ 1 ]);
            queueSearch();
	}
    });
    
    
    $(".infowindow").hide();
    $("#info_postalcode").show();
    $(".option > *").click(function () { selectInfoWindow(this); } );
    if( ajaxUpdate ) {
        $("#id_page").val( page );
        $("#id_min_postal_code").val( min_postal_code );
        $("#id_max_postal_code").val( max_postal_code);
        $("#id_min_size").val( min_size );
        $("#id_max_size").val( max_size ); 
        $("#id_min_rooms").val( min_rooms );
        $("#id_max_rooms").val( max_rooms );
        $("#id_min_price").val( min_price );
        $("#id_max_price").val( max_price );
        ajaxSearch();
    } else {
        updateResultList();
    }

    var paneButton = function(scope) { 
        if(!scope) scope = this;
        var current = $(scope).attr("rel");
        var hideAll = $(scope).hasClass("pane_button_selected");
        $(".pane_button").each(function() {
            if(this == scope && !hideAll) {
                if(!$(this).hasClass("pane_button_selected")) $(this).addClass("pane_button_selected");
            }else {
                if($(this).hasClass("pane_button_selected")) $(this).removeClass("pane_button_selected");
            }
        });

        $(".pane").each(function () {
            if($(this).hasClass(current) && !hideAll) {
                if(!$(this).hasClass("pane_visible")) $(this).addClass("pane_visible");
            } else {
                if($(this).hasClass("pane_visible")) $(this).removeClass("pane_visible");
            }
        });


    };

/*
    $(".pane_button").mouseover(function () { 
        var scope = this; 
        if (!paneChangeTimer || lastPaneButton != this)  {
            if(paneChangeTimer) {
                clearTimeout(paneChangeTimer); 
                paneChangeTimer = null;
            }
            paneChangeTimer =setTimeout(function () { 
                paneChangeTimer =null;  
//                console.log(paneChangeTimer);
                paneButton(scope); 
            }, 200);        
        }
        lastPaneButton = this;
    });
*/
    $(".pane_button").click(function() { paneButton(this); });

/*
    $(".pane > *").mouseover(function() { 
        var t = paneChangeTimer; 
        paneChangeTimer =null; 
        clearTimeout(t); 

        lastPaneButton =null;
//        console.log("Timer cleared"); 
    });
    $(".pane > *").mouseout(function() {
        if(paneChangeTimer) {
            clearTimeout(paneChangeTimer); 
            paneChangeTimer = null;
        }
        paneChangeTimer =setTimeout(function() {
            $(".pane_button").removeClass("pane_button_selected");
            $(".pane").removeClass("pane_visible");
        }, 100);
    });
*/
    lastHREF = location.href;
//    setInterval(function() { updateFromHistory(); }, 100);
});



$( document ).ajaxStart( function() {
    $( '#spinner' ).show();
}).ajaxStop( function() {
    $( '#spinner' ).hide();
});

