var link = '/index/compare?';
var position = 0;
$(document).ready(function(){
    $('#slider').slider({
        range: true, // necessary for creating a range slider
        min: 0, // minimum range of slider
        max: 100000, //maximimum range of slider
        values: [0, 100000], //initial range of slider
        step: 2500,
        slide: function(event, ui) { // This event is triggered on every mouse move during slide.
          

            if(ui.values[0]==0)
            {
                $('#sliderpricemin').html('$0');
            }
            else
            {
              $('#sliderpricemin').html('$' + ui.values[0]);
            }

            if(ui.values[1] == 100000)
            {
                $('#sliderpricemax').html('$100,000+');
            }
            else
            {
              $('#sliderpricemax').html('$' + ui.values[1]);
            }


        },
        stop: function(event, ui){//This event is triggered when the user stops sliding.
            loadMessage();
            var certifiedVal;
            if($('#Certified').is(':checked'))
            {
                certifiedVal = 1;
            }
            else
            {
                certifiedVal = 0;
            }

            var decendingVal;
            if($('#Decending').is(':checked'))
            {
                decendingVal = 1;
            }
            else
            {
                decendingVal = 0;
            }

            var dealerid = gup('dealerid');
            $.getJSON('index/getsearchconditions',{
                yearfrom: $('#YearFrom').val(),
                yearto: $('#YearTo').val(),
                make: $('#Makes').val(),
                model:$('#Models').val(),
                drivetype:$('#Drivetype').val(),
                sortby:$('#SortBy').val(),
                dealerid:dealerid,
                certified:certifiedVal,
                decending:decendingVal,
                pfrom: ui.values[0],
                pto: ui.values[1],
                isMake: 0
            },
            function(data){
                /*if(data[1].length == 0){
                    $('#list').html('No results.');
                }else{
                    renderList(data[1]);
                }*/
                renderList(data[1]);
                disableMessage();
            }
            );
        }
    });

   /* $('#sliderprice').html('$' + $('#slider').slider("values", 0) + ' - $' + $('#slider').slider("values", 1));*/

    if($('#slider').slider("values", 0)==0)
    {
        $('#sliderpricemin').html('$0');
    }
    else
    {
      $('#sliderpricemin').html('$' + $('#slider').slider("values", 0));
    }

    if($('#slider').slider("values", 1) == 100000)
    {
        $('#sliderpricemax').html('$100,000+');
    }
    else
    {
      $('#sliderpricemax').html('$' + $('#slider').slider("values", 1));
    }

    $('#YearFrom').change(function(){
        getSearchResult(0);
    });
    $('#YearTo').change(function(){
        getSearchResult(0);
    });
    $('#Makes').change(function(){
        getSearchResult(1);
    });

    $('#Models').change(function(){
        getSearchResult(0);
    });

    $('#Drivetype').change(function(){
        getSearchResult(0);
    });

    $('#Certified').change(function(){
        getSearchResult(0);
    });

    $('#SortBy').change(function(){
        getSearchResult(0);
    });

    $('#Decending').change(function(){
        getSearchResult(0);
    });

   row_effect();
   rowsimilar_effect();
});

function row_effect() {
	$(".row").bind({
    	mouseover: function() {
    		$(".row").removeClass("row_over");
    		$(this).addClass("row_over");
    		$(this).find(".hide").addClass("show");
    		$(this).find(".col_price").addClass("hide_bg");
    	},
    	mouseout: function() {
    		$(".row").removeClass("row_over");
    		$(".show").removeClass("show");
    		$(".col_price").removeClass("hide_bg");
    	},
    	click: function(e){
    		var avoid = /avoid/gi;
    		var clickedClass = e.target.className.toString();
    		if (clickedClass.match(avoid) == null)
    			window.location=$(this).find(".detail_link").attr("href");
    	}
    });       
}

function rowsimilar_effect() {
	$(".rowsimilar").bind({
    	mouseover: function() {
    		$(".rowsimilar").removeClass("row_over");
    		$(this).addClass("row_over");
    		$(this).find(".hide").addClass("show");
    		$(this).find(".col_price").addClass("hide_bg");
    	},
    	mouseout: function() {
    		$(".rowsimilar").removeClass("row_over");
    		$(".show").removeClass("show");
    		$(".col_price").removeClass("hide_bg");
    	},
    	click: function(e){
    		var avoid = /avoid/gi;
    		var clickedClass = e.target.className.toString();
    		if (clickedClass.match(avoid) == null)
    			window.location=$(this).find(".detail_link").attr("href");
    	}
    });
}

function getSearchResult(isMake){
	loadMessage();
        var certifiedVal;
        if($('#Certified').is(':checked'))
        {
            certifiedVal = 1;
        }
        else
        {
            certifiedVal = 0;
        }

        var decendingVal;
        if($('#Decending').is(':checked'))
        {
            decendingVal = 1;
        }
        else
        {
            decendingVal = 0;
        }

        var dealerid = gup('dealerid');
        $.getJSON('index/getsearchconditions',{
        yearfrom: $('#YearFrom').val(),
        yearto: $('#YearTo').val(),
        make: $('#Makes').val(),
        model:$('#Models').val(),
        drivetype:$('#Drivetype').val(),
        sortby:$('#SortBy').val(),
        dealerid:dealerid,
        certified:certifiedVal,
        decending:decendingVal,
        isMake: isMake,
        pfrom: $('#slider').slider("values", 0),
        pto: $('#slider').slider("values", 1)
    },
    function(data){
        if(data[0][0] == 'none'){
            $('#Models').html("<option value='0'>All Models</option>");
        }else if(data[0][0] != 'none1'){
            renderModel(data[0]);
        }

        renderList(data[1]);
        disableMessage();
    }
    );
}

function renderModel(model){
    var i = 0;
    var s = "<option value='0'>All Models</option>";
    while(i < model.length){
        s += "<option value='"+model[i][0]+"'>"+ model[i][1] + "</option>";
        i++;
    }
    $('#Models').html(s);
}

function renderYearTo(yearTo){
    var i = 0;
    var s = "<option value='0'></option>";
    while(i < yearTo.length){
        s += "<option value='"+yearTo[i][0]+"'>"+ yearTo[i][1] + "</option>";
        i++;
    }
    $('#YearTo').html(s);
}

function renderList(list){
    loadMessage();

    var i = 0;

    var content = "<form name='indexForm' method='Get' action='/index/compare'>";

    if(list.length == 0)
    {
        content += "No result found.";
    }
    else if(list.length == 1)
    {}
    else
    {
       content += "<div id='compareButton'>";
       content += "Please choose which cars to compare. (At least 2 and Max. 4 items)";
       content += "</div><br/>";
    }

    content += "<label>"+list.length+" Search Results</label>";
    content += "<div class='row_container'>";
    while(i < list.length){

        var PriceBasic = list[i]['Price'];
        var PriceFormattedStep1 = (Math.round(PriceBasic*100)/100 );
        var PriceFormatted = formatNumber (PriceFormattedStep1, 0);

        var SalePriceBasic = list[i]['SalePrice'];
        var SalePriceFormattedStep1 = (Math.round(SalePriceBasic*100)/100 );
        var SalePriceFormatted = formatNumber (SalePriceFormattedStep1, 0);

        content += "<div class='row'>";
        if(list.length > 1)
        {
            content += "<div class='col_select'><input id='preownedinvidcb-"+list[i]['Id']+"' name='preownedinvid[]' class='avoid' type='checkbox' value='"+list[i]['Id']+"' onclick='buildlinkFancyBox("+list[i]['Id']+");' /></div>";
        }
        content += "<div class='col_image'>";
        if (list[i]['MainPicture'] == null)
        	content += "<img width='113' height='1' scr='/media/images/preparation.jpg'/>";
        else
        	content += "<img width='113' height='86' src='"+list[i]['MainPicture']+"'/>";
        content += "</div>";
        content += "<div class='detail'>";
        if(list[i]['TrimLine'] != '')
        {
            content += "<div class='row_cell front_title_large'><span>"+
                list[i]['Year']+"</span> "+list[i]['MakeName']+" "+list[i]['ModelName']+" "+list[i]['TrimLine']+"</div>";
        }
        else
        {
            content += "<div class='row_cell front_title_large'><span>"+
                list[i]['Year']+"</span> "+list[i]['MakeName']+" "+list[i]['ModelName']+"</div>";
        }
        
        
        if (list[i]['Sold'] == 1)
            content += '<div class="detailprice">Sold</div>';
        else
            {
                content += '<div class="detailprice">';

                var today = new Date();

                today = today.format("isoDate");
                
                today = explode('-', today);

                today = new Date(today[0],today[1]-1,today[2]);

                var SalePriceFrom = explode('-', list[i]['SalePriceFrom']);

                SalePriceFrom = new Date(SalePriceFrom[0],SalePriceFrom[1]-1,SalePriceFrom[2]);                

                var SalePriceTo = explode('-', list[i]['SalePriceTo']);

                SalePriceTo = new Date(SalePriceTo[0],SalePriceTo[1]-1,SalePriceTo[2]);

                if (list[i]['SalePrice'] != '' && list[i]['SalePrice'] != 0 && (SalePriceFrom<=today && SalePriceTo>=today))
                {
                    content += "$"+SalePriceFormatted+"";                    
                    if (list[i]['Price'] != '' && list[i]['Price'] != 0)
                    {
                        content += '<div style="font-size:20px;font-weight:lighter;text-decoration:line-through;">';
                        content += "$"+PriceFormatted+"</div>";
                    }
                    else
                        content += 'Call for price';
                }
                else
                {
                    if (list[i]['Price'] != '' && list[i]['Price'] != 0)
                        content += "$"+PriceFormatted+"";
                    else
                        content += 'Call for price';
                }
                content += '</div>';
            }
            
        content += "<div class='col_content'>";
        content += "<div class='col_price";
        if (list[i]['Certified'] == 1)
        	content += " cert_"+list[i]['MakeName'].toLowerCase();
        content +=	"'>";
        content += "<div class='hide'><a class='detail_link' href='/index/detail/id/"+list[i]['Id']+"/"+list[i]['Year']+"-"+list[i]['MakeName']+"-"+list[i]['ModelName']+" '><img src='/media/images/viewdetails.png' border='0'/></a><br/><a href='/index/print/id/"+list[i]['Id']+"/"+list[i]['Year']+"-"+list[i]['MakeName']+"-"+list[i]['ModelName']+"' class='avoid' target='_blank' ><img src='/media/images/print.png' class=avoid' border='0' /></a></div>";
        content += "</div><div class='car_desc'>";
        content += "<div class='desc'><span>Stock #:</span>"+list[i]['StockNumber']+"</div>";
        if (list[i]['Kms'] != null)
        	content += "<div class='desc'><span>Mileage:</span>"+list[i]['Kms']+" km</div>";
        //content += "<div class='desc'><span>Engine:</span>"+list[i]['EngineSize']+"</div>";
        content += "<div class='desc'><span>Transmission:</span>"+list[i]['TransmissionName']+"</div>";
        //content += "<div class='desc'><span>Ext.Colour:</span>"+list[i]['ExteriorColourName']+"</div>";
        //content += "<div class='desc'><span>Int.Colour:</span>"+list[i]['InteriorColourName']+"</div>";
        content += "</div>";
        content += "<div class='col_space'></div>";
        content += "</div></div></div>";
        content += "<label style='visibility: hidden;'>"+(i+1)+"</label>";
        i++;
    }
    content += "</div></form>";
    disableMessage();
    $('#result').html(content);
    $('#list').fadeIn("slow");
    row_effect();
    link = '/index/compare?';
    position = 0;
}

function loadMessage(){
    $('#list').css({"display": "none"});
    $('#loading').css({'visibility':'visible'});
}

function disableMessage(){
    $('#loading').css({'visibility':'hidden'});
}

function buildlinkFancyBox(id)
{
    if($('#preownedinvidcb-'+id).attr('checked') == true )
        {
            position++;
            if(position == 1)
                {
                    link = link + 'preownedinvid[]=' + id;
                }
            else if(position >= 5)
                {}
            else
                {
                    link = link + '&preownedinvid[]=' + id;
                }
        }
     else
        {
            position--;
            if(position == 0 || position == 1)
                {
                    link = link.replace('preownedinvid[]=' + id, "");
                }
            else if(position >= 4)
                {}
            else
                {
                    link = link.replace('&preownedinvid[]=' + id, "");
                }
        }
    if(position >= 5)
        {
            position--;
            alert("Max. 4 items");
            document.getElementById('preownedinvidcb-'+id).checked = false;
            return false;
        }
    if(position >= 2)
        {
            $('#compareButton').html('<a id="CompareCars" href="'+link+'" >Compare</a> (Max. 4 items)');
            $("#CompareCars").fancybox({
                            'padding'			: 0,
                            'autoScale'			: false,
                            'transitionIn'		: 'none',
                            'transitionOut'		: 'none'
                    });
        }
    else
        {
            $('#compareButton').html("Please choose which cars to compare. (At least 2 and Max. 4 items)");
        }
}

function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

function explode (delimiter, string, limit) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']

    var emptyArray = { 0: '' };

    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' ) {
        return null;
    }

    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null ) {
        return false;
    }

    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}
