
String.prototype.trim = function() {
    return this.replace( /^\s+|\s+$/g , "" ).replace( /\s{2,}/g , " " );
};

var StopClosePanel = false;
var closertimer = 0;
var Timeout = 800;
var PriceMaximum = 1000000;
var YearMaximum = 2010;
var YearMinimum = 1900;
var MileageMaximum = 150000;
var ForExample;
var previousSuggestion = "";
var suggestionIndex = 0;
var isIE = /*@cc_on!@*/false;
function closePanel(pId) {
    if (!StopClosePanel)
        document.getElementById(pId).style.display = 'none';
}
function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if (e.style.display == 'block')
        e.style.display = 'none';
    else {
        e.style.display = 'block';
        if (id == 'countries_panel') {
            document.getElementById('language_panel').style.display = 'none';
        } else {
            document.getElementById('countries_panel').style.display = 'none';
        }

    }
    e.onmouseover = function() {
        StopClosePanel = true;
        try {
            window.clearTimeout(closetimer);
            // closetimer = null;
            closetimer = 0;
        } catch (e) {
        }
    // if (closetimer) {
    // window.clearTimeout(closetimer);
    // // closetimer = null;
    // closetimer = 0;
    // }
    }
    // e.onmouseout= function(){
    e.parentNode.onmouseout = function() {
        StopClosePanel = false;
        closetimer = window.setTimeout(function() {
            closePanel(id)
        }, Timeout);
    }

}
function setOdometer(pValue) {
    // try{ document.getElementById('od1').style.display='none'; }catch(err){}
    // try{ document.getElementById('od2').style.display='none'; }catch(err){}
    // try{ document.getElementById('od3').style.display='none'; }catch(err){}
    // try{ document.getElementById('od4').style.display='none'; }catch(err){}
    // try{ document.getElementById('od5').style.display='none'; }catch(err){}
    // try{ document.getElementById('od6').style.display='none'; }catch(err){}
    // try{ document.getElementById('od7').style.display='none'; }catch(err){}
    // try{ document.getElementById('od8').style.display='none'; }catch(err){}
    // try{ document.getElementById('od9').style.display='none'; }catch(err){}
    // try{ document.getElementById('od10').style.display='none'; }catch(err){}
//    document.getElementById('od1').style.display = 'none';
//    document.getElementById('od2').style.display = 'none';
//    document.getElementById('od3').style.display = 'none';
//    document.getElementById('od4').style.display = 'none';
//    document.getElementById('od5').style.display = 'none';
//    document.getElementById('od6').style.display = 'none';
//    document.getElementById('od7').style.display = 'none';
//    document.getElementById('od8').style.display = 'none';
//    document.getElementById('od9').style.display = 'none';
//    document.getElementById('od10').style.display = 'none';
    var br = pValue.replace(/\./g, '') * 1;
    // var numString=pValue.toString().trim().replace(/\./g,'' );
    var numString = br.toString();
    var numLength = numString.length;
    var odometerHTML = "";
    
    for ( var i = 0; i < numLength; i++) {
        //		document.getElementById("od" + i).innerHTML = numString.substr(-1, 1);
    	odometerHTML += '<span id="od' + ( numLength - i ) + '">' + numString.substr( i , 1 ) + '</span>';
    	
//    	document.getElementById("od" + i).innerHTML = numString.substr(numString.length-1, 1);
//        document.getElementById("od" + i).style.display = 'inline';
//        var upTo = numString.length - 1;
//        numString = numString.substr(0, upTo);
    }
    
    document.getElementById( "odometer" ).innerHTML = odometerHTML;
}

function submitWhat() {
    var changed = document.getElementById("text-search").value.trim();
    var selCountry = "";// document.getElementById("selCountry").value.trim();
    
    var arrayOptions = document.getElementsByTagName( "option" );
    
    if (document.getElementById("selCountry") == undefined)
        selCountry = "";
    else {
        selCountry = document.getElementById("selCountry").value.trim();
//    	for ( i = 0; i < arrayOptions.length; i++ )
//    		if ( arrayOptions[i].value == document.getElementById( "selCountry" ).value )
//    			selCountry = arrayOptions[i].innerHTML.trim();
    }
        
    var pozicijaDT = changed.indexOf(':');
    if (pozicijaDT!=-1){
        changed = changed.substr(pozicijaDT+1,changed.length);
    }
    changed += " " + selCountry;

    changed = changed.trim();

    if (changed.length != 0) {
        changed = changed.replace(/ /g, ";");
        var url = "";
        url += "/what-" + changed;

        if (window.location.pathname.indexOf("/visual-search") == 0)
            url += "/direction-visual;search";
        if (window.location.pathname.indexOf("/lite") == 0)
            url += "/direction-lite";
        
        window.location = url;
    }
    return false;
}

function doClear(theText) {
    theText.value = "";
    // uklanjamo div za prikaz rezultata
    document.getElementById('suggestion').style.display = 'none';
}

function suggest(e) {
    var keyCode = (window.event) ? event.keyCode : e.keyCode;
    var textColor1 = '#ffffff';
    var backgroundColor1 = '#004c7e';
    var textColor2 = '#000000';
    var backgroundColor2 = '#ffffff';
    
    if ( getRefference( "text-search" ).value.length == 0 ) {
    	getRefference( "suggestion" ).style.display = "none";
    	return false;
    }
    
    if ( keyCode == 27 ){
        if ( document.getElementById("text-search").value.trim().length == 0 ){        //ako je vec prazno sakri
            document.getElementById( "suggestion" ).style.display ='none';
        }
        document.getElementById("text-search").value='';
        return false;
    }
    
    if ( keyCode == 39 || keyCode == 37 ) return false;
    
    if ( keyCode == 38 ) {
    	// dohvatamo listu svih sugestija
    	var suggestionsArray = getRefference( "suggestion" ).getElementsByTagName( "li" );
    	
    	if ( suggestionsArray == null ) return false;
    	
    	if ( suggestionIndex > 1 ) {
    		suggestionsArray[suggestionIndex - 2].style.backgroundColor = backgroundColor1;
    		suggestionsArray[suggestionIndex - 2].style.color = textColor1;
    		suggestionsArray[suggestionIndex - 1].style.backgroundColor = backgroundColor2;
    		suggestionsArray[suggestionIndex - 1].style.color = textColor2;
    		suggestionIndex--;
    	}
    	
    }
    
    if ( keyCode == 40 ) {
    	// dohvatamo listu svih sugestija
    	var suggestionsArray = document.getElementById( "suggestion" ).getElementsByTagName( "li" );
    	
    	if ( suggestionsArray == null ) return false;
    	
    	if ( suggestionIndex < suggestionsArray.length ) {
    		if ( suggestionIndex > 0 ) {
    			suggestionsArray[suggestionIndex - 1].style.backgroundColor = backgroundColor2;
        		suggestionsArray[suggestionIndex - 1].style.color = textColor2;
    		}
    			
    		suggestionsArray[suggestionIndex].style.backgroundColor = backgroundColor1;
    		suggestionsArray[suggestionIndex].style.color = textColor1;
    		
    		suggestionIndex++;
    	}
    	
    }
    
    if ( keyCode == 13 ) {
    	// dohvatamo listu svih sugestija
    	var suggestionsArray = document.getElementById( "suggestion" ).getElementsByTagName( "li" );
    	document.getElementById( "text-search" ).value = suggestionsArray[suggestionIndex - 1].innerHTML.replace( /<[\/]?[bB]>/gi , '' ).trim();
    	document.getElementById( "suggestion" ).style.display = "none";
    	submitWhat();
    	return false;
    }

    document.getElementById("suggestion").style.display='block';
    var query = document.getElementById("text-search").value.toLowerCase();
    
    if (query.length == 0)
        return false;
    else {

        var url = "/SuggestionAjaxGetter.ajax?q="
        + document.getElementById("text-search").value.toLowerCase();
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
            // Safari
            xmlhttpML = new XMLHttpRequest();
        } else {// code for IE6, IE5
            xmlhttpML = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttpML.onreadystatechange = function() {
            if (xmlhttpML.readyState == 4 && xmlhttpML.status == 200) {
                var suggestions = eval( decodeURI( xmlhttpML.responseText ) );
                
                // if there is no suggestions for search criteria, hide suggestions div
                if ( suggestions.length == 0 )
                	getRefference( "suggestion" ).style.display = "none";
                else {
                	// clearing previous suggestions
                	clearContent( "suggestion" );
                	
                	// creating ul element
                	getRefference( "suggestion" ).appendChild( createElementWithAttributes( "ul" , { } ) );
                	
                	// appending new results
                	for ( i = 0; i < suggestions.length; i++ ) {
                		var suggestion =  createElementWithAttributes( "li" , { "innerHTML" : suggestions[i].trim().replace( getRefference( "text-search" ).value.trim() , "<b>" + getRefference( "text-search" ).value.trim() + "</b>" ) } );
                		suggestion.onclick = function() {
                			setSuggestionTo( this );
                		}
                		getRefference( "suggestion" ).getElementsByTagName("ul")[0].appendChild( suggestion );
                	}
                }
                
            	/*var lists = decodeURI(xmlhttpML.responseText).split("\n");
                var innertHtml = "<div class=\"suggestions\"><ul id=\"suggestions\">";
                if (location.href.indexOf('/lite')!=-1||location.href.indexOf('/light')!=-1){
                    innertHtml = "<div class=\"suggestionsLIndex\"><ul id=\"suggestions\">";
                }
				
                var valuesArray = new Array();
                var valuesCounter = 0;
                
                for(i = 0; i < lists.length; i++)
                {
                    var tmp = lists[i];
                    if ( tmp == "" ) continue;
                    var split = tmp.split(" ");
					
                    for(j = 0; j < split.length; j++)
                    {
                        spl = split[j];
                        sp = spl.replace(query,"<b>" + query + "</b>");
                        tmp = tmp.replace(spl,sp);
                    }
                    
                    innertHtml += "<li " + "name=\"" + lists[i] + "\"" +  " id=suggestion_" + i + " " +  "onclick=" + "setSuggestionTo(this);" + ">" + tmp + "</li>";
                    valuesArray[valuesCounter] = tmp;
                    valuesCounter++;
                    
                }
                innertHtml += "</div>";
                
                if ( valuesArray[0].length == 1 ) innertHtml = "";
                
                document.getElementById("suggestion").innerHTML = innertHtml;*/// "<div class=\"suggestions\"><ul><li>Mercedes <strong>Benz</strong> C class</li></div>";
            // console.log(lists);
            // get array of make
            }
        }
        
        
        if ( query.substr( 0 , query.length ) != previousSuggestion ) {
        	xmlhttpML.open("GET", url, true);
        	xmlhttpML.send( null );
        	suggestionIndex = 0;
        }
    }
}

function setSuggestionTo(suggestion)
{
	var selCountry = "";// document.getElementById("selCountry").value.trim();

    if (document.getElementById("selCountry") == undefined)
        selCountry = "";
    else
        selCountry = document.getElementById("selCountry").value.trim();
	
	var text = suggestion.innerHTML;
	
	// brisemo HTML karaktere i menjamo razmake sa ;
	text = text.replace( /<[\/]?[a-z]+>/gi, '' );
	document.getElementById( "text-search" ).value = text;
	text = text.replace( / /g, ';' );
	
    var url = "";
    url += "/what-" + text+";"+selCountry;

    if (window.location.pathname.indexOf("/visual-search") == 0)
        url += "/direction-visual;search";
    if (window.location.pathname.indexOf("/lite") == 0)
        url += "/direction-light";
    window.location = url.toLowerCase();
}

function getMetaContents(mn){
	var m = document.getElementsByTagName('meta');
	for(var i in m){
		if ( m[i].name != null )
			if(  m[i].name == mn){
				return m[i].content;
			}
	}
	return "en";
}

//potrebna f-ja na result, visual, lightresult stranicama
function showMoreF(elemId,moreless){
    //	var newFooterLabel = document.getElementById(elemId).parentNode.getAttribute("title");
    var elemName = elemId.replace('more','');
    var lang = getMetaContents("meta-language");
    
    var values = document.getElementById('fil'+elemName).getElementsByTagName( "li" );
	var filHeader = values[0];
	var filHeaderLabel = filHeader.getElementsByTagName("h2")[0].innerHTML;
	var lastLi = values.length;
	var filFooter = values[lastLi - 1];
//	var filHeaderLabel = filHeader[0].innerHTML;
//	var lastLi = values.length;
//	var filFooter = values[lastLi-1];
    
//    if ( isIE ) {
//    	var filHeader=document.getElementById('fil'+elemName).children[0];
//    	var filHeaderLabel = filHeader.children[0].innerHTML;
//    	var lastLi = document.getElementById('fil'+elemName).children.length;
//    	var filFooter=document.getElementById('fil'+elemName).children[lastLi-1];
//    } else {
//    	var filHeader=document.getElementById('fil'+elemName).childNodes[1];
//    	var filHeaderLabel = filHeader.childNodes[1].innerHTML;
//        var lastLi = document.getElementById('fil'+elemName).childNodes.length;
//        var filFooter=document.getElementById('fil'+elemName).childNodes[lastLi-2];
//    }
    var filFooterLabel = document.getElementById(elemId).parentNode.getAttribute("title");
//    if ( isIE )
//    	var newParentTitle = filFooter.children[0].innerHTML;
//    else
//    	var newParentTitle = filFooter.childNodes[1].innerHTML;
 	//bleja
    var newParentTitle = filFooter.getElementsByTagName("a")[0].innerHTML;
    newParentTitle = newParentTitle.substring( 0 , newParentTitle.length - 2 );
    //    document.getElementById(elemId).parentNode.setAttribute("title",newParentTitle);
    var innerHtml ='<li><h2>'+filHeaderLabel+'</h2></li>';
    //ajax
    var xmlhttpML;
    var url=location.href.replace(/\#/g,'').replace("http://", "");
    var url="/ViewMore.ajax?what="+elemName+"&lang="+lang+"&view="+moreless+"&url="+url;
    //    http://www.ooyyo.ie/ViewMore.ajax?what=bodytype&lang=en&view=more&url=www.ooyyo.ie/used-cars/audi/ireland/sort-mileage+asc
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttpML=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttpML=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttpML.onreadystatechange=function()
    {
        if (xmlhttpML.readyState==4 && xmlhttpML.status==200)
        {
            var lists = decodeURI(xmlhttpML.responseText).split(";"); // get response message
            var liTag =[];
            var oneLiTag = [];
            for (var i=0;i<lists.length;i++){
                oneLiTag= lists[i].split('#');
                if ( oneLiTag == '' ) continue;
                innerHtml+='<li><span>'+oneLiTag[1]+'</span> <a href="'+oneLiTag[2]+'">'+oneLiTag[0]+'</a></li>'
            }
            
            var sign = "";
            
            if (moreless=='more'){
                moreless='less';
                sign = "▲";
            }else{
                moreless='more';
                sign = "▼";
            }
            innerHtml+='<li title="'+newParentTitle+'"><a onclick="showMoreF(this.id,this.name); return false;" name="'+moreless+'" id="more'+elemName+'" class="vmore" href="#" title="'+filFooterLabel+'" >'+filFooterLabel + " " + sign +'</a></li>';
            document.getElementById('fil'+elemName).innerHTML = innerHtml;

        }
    };
    xmlhttpML.open("GET",url,true);
    xmlhttpML.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
    xmlhttpML.send( null );

}

function replaceHash(url)
{
	var putanja = url.href;
    putanja = putanja.replace(/\#/g, "/");
    window.location = putanja;
}

function setSort(elem){
    var elemName = elem.name;
    var inx = location.href.indexOf('sort-'+elemName);
    var inxSort = location.href.indexOf('sort-');
    var url = location.href;
    if (inx==-1) {
        //nema tog sorta,radi se o novom
        if (inxSort!=-1) {
            url = url.substr(0,inxSort-1);//sklanja stari sort
        }
        if (url.indexOf('page-')!=-1){
            url = url.substr(0,url.indexOf('page-'));
        }
        if (url.substr(-1, 1)=='/'){
            url = url.substr(0,url.length-1)
        }
        url +='/sort-'+elemName+'+asc';
    } else {
        if(url.indexOf('asc',inx)!=-1){
            //replace to 'desc'
            url = url.replace('asc','desc');
            elem.innerHTML = elem.innerHTML.replace('▲','▼');
        }else{
            //replace to 'asc'
            url = url.replace('desc','asc');
            elem.innerHTML = elem.innerHTML.replace('▼','▲');
        }

        //remove 'page-'
        if (url.indexOf('page-')!=-1){
            url = url.substr(0,url.indexOf('page-')-1);
        }
    }
    location = url.toLowerCase();
   
}

function showResultsRefineSearch(){
    var url = location.href.replace(/\#/g,'');
    var inx = url.indexOf('sort-');
    var sortLabel = '';
    if (inx!=-1){
        sortLabel = url.substr(inx-1,url.length);
        url = url.substr(0,inx-1);
    }


    var priceFrom = document.getElementById('selPriceFrom').value;
    var priceTo = document.getElementById('selPriceTo').value;
    var yearFrom = document.getElementById('selYearFrom').value;
    var yearTo = document.getElementById('selYearTo').value;
    var mileageFrom = document.getElementById('selMileageFrom').value;
    var mileageTo = document.getElementById('selMileageTo').value;

    //    // set year
    Year='';
    if (yearFrom != undefined && yearFrom != "any" &&  yearTo == "any" ){
        //        Year = yearFrom + "-" + YearMaximum;
        Year = yearFrom ;
    }else if (yearFrom != undefined && yearFrom != "any" && yearTo != undefined && yearTo != "any" ){
        Year = yearFrom + "-" + yearTo;
    }else if ( yearFrom == "any" && yearTo != undefined && yearTo != "any" ){
        Year = YearMinimum + "-" + yearTo;
    }

    // set price
    Price='';
    if (priceFrom != undefined && priceFrom != "any" &&  priceTo == "any" ){
        //        Price = priceFrom.replace(/\+/,"") + "-" + PriceMaximum;
        Price = priceFrom.replace(/\+/,"") ;
    }else if (priceFrom != undefined && priceFrom != "any" && priceTo != undefined && priceTo != "any" ){
        Price = priceFrom.replace(/\+/,"") + "-" + priceTo;
    }else if ( priceFrom == "any" && priceTo != undefined && priceTo != "any" ){
        Price = 0 + "-" + priceTo;
    }
    //
    //    // set mileage
    Mileage='';
    if (mileageFrom != undefined && mileageFrom != "any" &&  mileageTo == "any" ){
        //        Mileage = mileageFrom.replace(/\+/,"") + "-" + MileageMaximum;
        Mileage = mileageFrom.replace(/\+/,"") ;
    }else if (mileageFrom != undefined && mileageFrom != "any" && mileageTo != undefined && mileageTo != "any" ){
        Mileage = mileageFrom.replace(/\+/,"") + "-" + mileageTo;
    }else if ( mileageFrom == "any" && mileageTo != undefined && mileageTo != "any" ){
        Mileage = 0 + "-" + mileageTo;
    }

    if ( url.substr( -1 , 1 ) == '/' ) {            //sklanja '/' ako ima na kraju
        url = url.substr( 0, url.length - 1 );
    }


    //makni prethodni price
    var podelaUrl = url.split('/');
    for (var a=podelaUrl.length-1;a>0;a--){
        if(podelaUrl[a].indexOf('price-')!=-1 || podelaUrl[a].indexOf('mileage-')!=-1 || podelaUrl[a].indexOf('year-')!=-1 || podelaUrl[a].indexOf('page-')!=-1){
            podelaUrl.splice(a,1);
        }
    }
    url = podelaUrl.join('/');


    url = url+
    (Price?'/price-'+Price.replace('-','+'):'')+
    (Year?'/year-'+Year.replace('-','+'):'')+
    (Mileage?'/mileage-'+Mileage.replace('-','+'):'');
    if (sortLabel!=''){
        if (sortLabel.indexOf('page-')!=-1){
            sortLabel=sortLabel.substr(0,sortLabel.indexOf('page-')-1);
        }
        url+=sortLabel;
    }

    location = url.toLowerCase();
}

function submitQSPanel(){
    //collectData
    var make = document.getElementById('selMake').value;
    var model = document.getElementById('selModel').value;
    var fuel = document.getElementById('selFuel').value;
    var zip = '';
    try {
        zip = document.getElementById('selZip').value;
    }
    catch(e){}
    var countryLabel = document.getElementById('choosenCountry').innerHTML;
    var state ='';
    try {
        state = document.getElementById('choosenState').innerHTML;
    }
    catch(e){}
    countryLabel = (state?countryLabel+'-'+state:countryLabel);

    if (make != undefined && make != "any" ){}
    else{
        make='';
    }
    if (model != undefined && model != "any" ){}
    else{
        model='';
    }
    if (fuel != undefined && fuel != "any" ){}
    else{
        fuel='';
    }
    //do not set zip if it's different than USA
    if (document.getElementById('choosenCountry').className != 'united states'){
        zip='';
    }

    // make url
    var url = document.getElementById('QSPshowResults').name; //allready has "/"

    url += (model?'/'+make+'-'+model:(make?'/'+make:''))+
    "/"+countryLabel+
    //(Price?'/price-'+Price.replace('-','+'):'')+
    //(Year?'/year-'+Year.replace('-','+'):'')+
    //(Mileage?'/mileage-'+Mileage.replace('-','+'):'')+
    (fuel?'/fueltype-'+fuel:'')+
    (zip?'/zip-'+zip:'');
    //(Option?'/options-'+Option.replace(/\,/g,'-'):'');

    url = url.toLowerCase().replace(/ /g, "+");

    window.location = url.toLowerCase();
    return false;
}

function QSPcreateMakeList(){
    //delete previous make list
	if ( isIE )
		var optionAny = document.getElementById('selMake').children[0];
	else
		var optionAny = document.getElementById('selMake').childNodes[1];
    document.getElementById('selMake').innerHTML = '';
    //delete previous model list
    if ( isIE )
    	var optionAnyModel = document.getElementById('selModel').children[0];
    else
    	var optionAnyModel = document.getElementById('selModel').childNodes[1];
    document.getElementById('selModel').innerHTML = '<option value="any" selected="selected">'+optionAnyModel.innerHTML+'</option>';
    
    document.getElementById('selMake').setAttribute('disabled', 'disabled');

    var country = document.getElementById('choosenCountry').className;
    //    var selectedCountry = document.getElementById('selCountry').value;
    //    var arrayOptions = document.getElementsByTagName('option');
    //    Country=selectedCountry.toString();
    ////    CountryLabel=document.getElementById('selCountry').getAttribute('label');
    //    for (var i=0;i<arrayOptions.length;i++){
    //        if(arrayOptions[i].value==selectedCountry){
    //            if (arrayOptions[i].parentNode.id=='usa'){
    //                Country="united states&state="+selectedCountry;
    //            }
    //            if (arrayOptions[i].value==selectedCountry){
    //                CountryLabel=arrayOptions[i].innerHTML;
    //            }
    //
    //        }
    //    }
    var state = '';
    try{
        state = document.getElementById('choosenState').className;
    }
    catch(e){}
    if (state!=''){
        country= country+'&state='+state;
    }


    var xmlhttpML;
    var url="/QSMakeGetter.ajax?country="+country;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttpML=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttpML=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttpML.onreadystatechange=function()
    {
        if (xmlhttpML.readyState==4 && xmlhttpML.status==200)
        {
            var lists = decodeURI(xmlhttpML.responseText).split("#"); // get array of make
            var lists_0 = lists[0].split(";");
            var innerHtml ='<option value="any" selected="selected">'+optionAny.innerHTML+'</option>';
            for (var j=0;j<lists_0.length;j++){
                innerHtml+='<option value="'+lists_0[j]+'">'+capitaliseFirstLetter(lists_0[j])+'</option>';
            }
            var lists_1 = lists[1].split(";");
            innerHtml+='<option value="'+lists_1[0]+'" class="separator">'+capitaliseFirstLetter(lists_1[0])+'</option>';
            for (var k=1;k<lists_1.length;k++){
                innerHtml+='<option value="'+lists_1[k]+'">'+capitaliseFirstLetter(lists_1[k])+'</option>';
            }

            document.getElementById('selMake').innerHTML= innerHtml;
            document.getElementById('selMake').removeAttribute('disabled');
        }
    }
    xmlhttpML.open("GET",url,true);
    xmlhttpML.send( null );

}

function toggleQSPanel(){
    var QSP = document.getElementById('qsp');
    if (QSP.style.display=='block'){
        QSP.style.display='none';
    }else {
        QSPcreateMakeList();
        QSP.style.display='block';
    }
}




function QSPcreateModelList(){
    //delete previous model list
	if ( isIE )
		var optionAnyModel = document.getElementById('selModel').children[0];
	else
		var optionAnyModel = document.getElementById('selModel').childNodes[1];
	
    //    document.getElementById('selModel').innerHTML = '<option value="any" selected="selected">'+optionAnyModel.innerHTML+'</option>';
    document.getElementById('selModel').innerHTML = '';

    document.getElementById('selModel').setAttribute('disabled', 'disabled');
    var country = document.getElementById('choosenCountry').className;
    var make = document.getElementById('selMake').value;
    var xmlhttpML;
    var url="/QSModelGetter.ajax?country="+country+"&make="+make;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttpML=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttpML=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttpML.onreadystatechange=function()
    {
        if (xmlhttpML.readyState==4 && xmlhttpML.status==200)
        {
            var lists = decodeURI(xmlhttpML.responseText).split("#"); // get array of models
            var lists_0 = lists[0].split(";");
            var innerHtml ='<option value="any" selected="selected">'+optionAnyModel.innerHTML+'</option>';
            for (var j=0;j<lists_0.length;j++){
                innerHtml+='<option value="'+lists_0[j]+'">'+capitaliseFirstLetter(lists_0[j])+'</option>';
            }

            document.getElementById('selModel').innerHTML= innerHtml;
            document.getElementById('selModel').removeAttribute('disabled');
        }
    }
    xmlhttpML.open("GET",url,true);
    xmlhttpML.send( null );

}
function changeCountryOrState(){
    var choosenCountry = document.getElementById('choosenCountry').innerHTML;
    var choosenState = '';
    var url = location.href;

    var selectedCountry = document.getElementById('selCountry').value;
    var arrayOptions = document.getElementsByTagName('option');
    var country=selectedCountry.toString();
    //    CountryLabel=document.getElementById('selCountry').getAttribute('label');
    for (var i=0;i<arrayOptions.length;i++){
        if(arrayOptions[i].value==selectedCountry){
            country=arrayOptions[i].innerHTML;
        }
    }
    
    var state = '';
    try{
        choosenState = document.getElementById( 'choosenState' ).innerHTML;
    }
    catch(er){    }
    try{
        state = document.getElementById( 'selState' ).value;
    }
    catch(er){    }
    for (var a=0;a<arrayOptions.length;a++){
        if(arrayOptions[a].value==state){
            state=arrayOptions[a].innerHTML;
        }
    }
    if (selectedCountry!='any'){                        //menjanje country, obrisati city
        var tempUrl=decodeURI(url).replace(/\+/g,' ');
        var tempUrlParts = tempUrl.split('/');
        for ( var b = tempUrlParts.length - 1; b > 0; b-- ){
            if ( tempUrlParts[b].indexOf( choosenCountry ) != -1 ){
                tempUrlParts[b] = country;
            }
            if (tempUrlParts[b].indexOf('page-')!=-1){      //page se sklanja kod promene zemlje
                tempUrlParts.splice(b,1);
            }
        }
        //        url = tempUrl.replace(choosenCountry,country);
        url = tempUrlParts.join('/');
    }
    if (choosenState!='any' && choosenState!=''){
        var tempUrl=decodeURI(url).replace(/\+/g,' ');
        url = tempUrl.replace(choosenState,state);
    }
    if (choosenState=='' && state!=''){     //state nije postojao, dodaje se
        var tempSwitch = choosenCountry+'-'+state;
        var tempUrl=decodeURI(url).replace(/\+/g,' ');
        url = tempUrl.replace(choosenCountry,tempSwitch);
    }
    
    var choosenCity = "";
    try {
    	choosenCity = document.getElementById( "choosenCity" ).innerHTML;
    } catch (e) {};
    
    if ( choosenCity != "" ) {
    	var tempUrl = decodeURI(url).replace( /\+/g , '' );
    	url = tempUrl.replace( "-" + choosenCity , "" );
    }
    
    url = url.replace(/\ /g,'+');
    
    location = url.toLowerCase();
}

//window.onload = function() {
//
//}

function createMakeList(){
    //delete previous make,Model list
    document.getElementById('selMake').innerHTML =""; 
    document.getElementById('selModel').innerHTML="";
    
    if ( isIE )
    	var optionAny = document.getElementById('selFuel').children[0];
    else
    	var optionAny = document.getElementById('selFuel').childNodes[1];
    document.getElementById('selModel').appendChild(optionAny.cloneNode(true));
    optionAny = optionAny.cloneNode(true);

    document.getElementById('selMake').setAttribute('disabled', 'disabled');
//    arrayRQElements.push('selMake');
    collectData();
    var url="/QSMakeGetter.ajax?country="+Country;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttpML=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttpML=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttpML.onreadystatechange=function()
      {
      if (xmlhttpML.readyState==4 && xmlhttpML.status==200)
        {
            var lists = decodeURI(xmlhttpML.responseText).split("#"); // get array of make
            var lists_0 = lists[0].split(";");
            document.getElementById('selMake').appendChild(optionAny.cloneNode(true)); //prvo any
            var letter = "";
            for (var j=0;j<lists_0.length;j++){
                if ( lists_0[j].substr( 0 , 1 ) != letter ) {
                	letter = lists_0[j].substr( 0 , 1 );
                	var optgroup = document.createElement("optgroup");
                	optgroup.label = letter.toUpperCase();
                	document.getElementById("selMake").appendChild( optgroup );
                }
            	optionAny.value = lists_0[j];
                optionAny.innerHTML = capitaliseFirstLetter(lists_0[j]);
                document.getElementById('selMake').appendChild(optionAny.cloneNode(true));
            }
            var lists_1 = lists[1].split(";");
//            optionAny.value = lists_1[0];
            optionAny.value = "any";
//            optionAny.className="separator";
            optionAny.className="";
//            optionAny.innerHTML=capitaliseFirstLetter(lists_1[0]);
            optionAny.innerHTML = "------------------------------";
            document.getElementById('selMake').appendChild(optionAny.cloneNode(true));
            for (var k=1;k<lists_1.length;k++){
                optionAny.className='';
                optionAny.value = lists_1[k];
                optionAny.innerHTML = capitaliseFirstLetter(lists_1[k]);
                document.getElementById('selMake').appendChild(optionAny.cloneNode(true));
            }
            document.getElementById('selMake').removeAttribute('disabled');

        }
      }
    xmlhttpML.open("GET",url,true);
    xmlhttpML.send( null );

}
function createModelList(){
        //delete previous model list
	if ( isIE )
		var optionAny = document.getElementById('selFuel').children[0];
	else
		var optionAny = document.getElementById('selFuel').childNodes[1];
	
    document.getElementById('selModel').innerHTML = "";
    document.getElementById('selModel').setAttribute('disabled', 'disabled');
    optionAny = optionAny.cloneNode(true);
//    arrayRQElements.push('selMake');
    collectData();
    var url="/QSModelGetter.ajax?country="+Country+"&make="+Make;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttpML=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttpML=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttpML.onreadystatechange=function()
      {
      if (xmlhttpML.readyState==4 && xmlhttpML.status==200)
        {
            var lists = decodeURI(xmlhttpML.responseText).split("#"); // get array of models
            var lists_0 = lists[0].split(";");
            document.getElementById('selModel').appendChild(optionAny.cloneNode(true)); //prvo anyoptionAny
            for (var j=0;j<lists_0.length;j++){
                optionAny.value = lists_0[j];
                optionAny.innerHTML = capitaliseFirstLetter(lists_0[j]);
                document.getElementById('selModel').appendChild(optionAny.cloneNode(true));
//                innerHtml+='<option value="'+lists_0[j]+'">'+capitaliseFirstLetter(lists_0[j])+'</option>';
            }
//            var lists_1 = lists[1].split(";");
//            innerHtml+='<option value="'+lists_1[0]+'" class="separator">'+capitaliseFirstLetter(lists_1[0])+'</option>';
//            for (var k=1;k<lists_1.length;k++){
//                innerHtml+='<option value="'+lists_1[k]+'">'+capitaliseFirstLetter(lists_1[k])+'</option>';
//            }

//            document.getElementById('selModel').innerHTML= innerHtml;
            document.getElementById('selModel').removeAttribute('disabled');
        }
      }
    xmlhttpML.open("GET",url,true);
    xmlhttpML.send(null);

}

function ajaxCounting(element, elementName) {
	element.setAttribute('disabled', 'disabled');
	arrayRQElements.push(elementName);
	collectData();
	var url = "/QSCounting.ajax?country=" + Country
			+ (Make ? '&make=' + Make : '') + (Model ? '&model=' + Model : '')
			+ (MaxPrice ? '&price=0-' + MaxPrice : '')
			+ (YearFrom ? '&year=' + YearFrom + '-' + YearMax : '')
			+ (MaxMileage ? '&mileage=0-' + MaxMileage : '')
			+ (Fuel ? '&fueltype=' + Fuel : '');
	var xmlhttp;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			element.removeAttribute('disabled');
			document.getElementById(elementName).removeAttribute('disabled');
			if (arrayRQElements[arrayRQElements.length - 1] == elementName) {
				setOdometer(decodeURI(xmlhttp.responseText));
				arrayRQElements.length = 0;
			}
			if (elementName == 'selCountry') {
				CountryLabelNumber = xmlhttp.responseText;
				changeCountryOfSearch();
			}
		}
	};
	xmlhttp.open("GET", url, true);
	xmlhttp.send(null);
}

function changeCountryOfSearch(){
    var nowTxt = document.getElementById('countryOfSearch').innerHTML;
    var end = nowTxt.indexOf('</');
    nowTxt=CountryLabel+': <strong>'+CountryLabelNumber+nowTxt.substr(end);
    document.getElementById('countryOfSearch').innerHTML = nowTxt;
}

function resetSuggestion() {
	// samo ukoliko nista nije uneto u polje za pretragu, resetuj vrednost
	if ( document.getElementById('text-search').value.length == 0 )
		document.getElementById('text-search').value = ForExample;
	
	// pozivamo skrivanje diva sa zakasnjenjem od 150 milisekundi da bi se prvo izvrsila onclick funkcija nad divom sa sugestijama
	setTimeout( "document.getElementById('suggestion').style.display = 'none';" , 150 );
	
}

function submitQuickSearch() {
    collectData();
    // make url
    var url = document.getElementById('QSSubmit').name; // allready has "/"

    url += 
        (Model?'/'+Make+'-'+Model:(Make?'/'+Make:''))+
        "/"+CountryLabelURL+
        (MaxPrice?'/price-0+'+MaxPrice:'')+
        (YearFrom?'/year-'+YearFrom+'+'+YearMax:'')+
        (MaxMileage?'/mileage-0+'+MaxMileage:'')+
        (Fuel?'/fueltype-'+Fuel:'') +
        (ZipCode?'/zip-' + ZipCode : '');
    
    url = url.toLowerCase().replace(/ /g, "+");
    
    window.location = url.toLowerCase();
    return false;
}

function resetAll(){
	if ( isIE )
		var optionAny = document.getElementById('selFuel').children[0];
	else
		var optionAny = document.getElementById('selFuel').childNodes[1];
	document.getElementById('selMake').innerHTML =""; 
    document.getElementById('selModel').innerHTML="";
    document.getElementById('selMake').appendChild(optionAny.cloneNode(true));
	document.getElementById('selModel').appendChild(optionAny.cloneNode(true));
    resetRefiners();
}

function resetRefiners(){
	document.getElementById('selMaxPrice').selectedIndex = 0;
	document.getElementById('selYearFrom').selectedIndex = 0;
	document.getElementById('selMaxMileage').selectedIndex = 0;
	document.getElementById('selFuel').selectedIndex = 0;
}

/* funkcija za sakrivanje slika koje se ne ucitavaju na visual search stranici */
function hideImage(image) {
	// obrisi div u kome se nalazi slika ukoliko pukne ucitavanje
	if ( navigator.appName != 'Microsoft Internet Explorer' )
		image.parentNode.parentNode.parentNode.parentNode.removeChild( image.parentNode.parentNode.parentNode );
}

/* funkcija za racunanje od do opsega koja se koristi u filterima na advanced searchu, na naslovnoj, u boxu na strani sa rezultatima */
function calculateRange( idFrom , idTo ) {
	// uzivamo vrednosti svih opcija koje se mogu pojaviti
	var values = document.getElementById( idFrom ).getElementsByTagName( "option" );
    // uzimamo prvi elemenat, njega cemo dalje klonirati
    var any = values[0];
    // brisemo sadrzaj select boxa to
    document.getElementById( idTo ).options.length = 0;
    // dodajemo any kao prvi elemenat
    document.getElementById( idTo ).appendChild( any.cloneNode( true ) );
    // kupimo vrednost odabrane opcije u select boxu from
    var from = parseInt( document.getElementById( idFrom ).value );
    
    // prolazimo kroz niz opcija
    for ( i = 1; i < values.length; i++ ) {
    	
    	// kloniramo opciju
    	var anyClone = any.cloneNode(true);
		anyClone.value = parseInt( values[i].value );
		anyClone.innerHTML = values[i].innerHTML;
    	
		// ukoliko je vrednost from polja any, dodajemo sve opcije iz niza values
		// u suprotnom, proveravamo da li je ta opcija veca od odabrane u from select boxu
		// pa ukoliko jeste, dodajemo je
    	if ( document.getElementById( idFrom ).value == "any" )
    		document.getElementById( idTo ).appendChild( anyClone );
    	else {
    		if ( parseInt( values[i].value ) >= from ) {
        		var anyClone = any.cloneNode( true );
        		anyClone.value = parseInt( values[i].value );
        		anyClone.innerHTML = values[i].innerHTML;
        		document.getElementById( idTo ).appendChild( anyClone );
        	}
    	}
    	
    	// ukoliko je poslednji znak +, ukljanjamo ga
    	if ( anyClone.innerHTML.substring( anyClone.innerHTML.length - 1 ) == "+" )
			anyClone.innerHTML = anyClone.innerHTML.substring( 0 , anyClone.innerHTML.length - 1 );
    	
    }
    
    // selektujemo prvi elemenat
    document.getElementById( idTo ).selectedIndex = 0;
}

/* Metoda koja updateuje text prethodne sugestije svaki put kada korisnik nesto unese */
function updateSuggestion() {
	previousSuggestion = document.getElementById( "text-search" ).value.toLowerCase();
}

function replaceImage( reference , externalURL , errorImageURL ) {
    if ( navigator.appName == 'Microsoft Internet Explorer' ) {
    	
    	// setting on error image to URL of error image
    	reference.src = errorImageURL;
    	
    } else {
    	
    	// duplicate check
    	if ( reference.src == externalURL ) {
    		reference.src = errorImageURL;
    		return;
    	}
    	
    	// creating image object
        reference.src = externalURL;
    	reference.onerror = function() {
    		reference.src = errorImageURL;
        }
    	
    }
}

function countDown() {
	// old counter value
	var counterLength = getRefference( "odometer" ).getElementsByTagName( "span" ).length;
	// clearing previous content
	clearContent( "odometer" );
	// setting new number in odometer
	for ( i = 0; i < counterLength; i++ )
		appendElement( "odometer" , createElementWithAttributes( "span" , { "innerHTML" : Math.ceil( Math.random() * 9 ) } ) );
}

function getRefference( id ) {
	return document.getElementById( id );
}

function appendElement( id , child ) {
	document.getElementById( id ).appendChild( child );
}

function clearContent( id ) {
	document.getElementById( id ).innerHTML = "";
}

function createElementWithAttributes( type , attributes ) {
	var element = document.createElement( type );
	
	for ( key in attributes )
		element[key] = attributes[key];
	
	return element;
}

function getResultAjaxURLCounterParameters() {
	
	var url = "";
	
	if ( getRefference( "choosenCountry" ) != null )
		url += ( "country=" + getRefference( "choosenCountry" ).innerHTML + "&" );
	
	if ( getRefference( "choosenState" ) != null )
		url += ( "state=" + getRefference( "choosenState" ).innerHTML + "&" );
	
	if ( getRefference( "choosenCity" ) != null )
		url += ( "city=" + getRefference( "choosenCity" ).innerHTML + "&" );
	
	if ( getRefference( "choosenModel" ) != null )
		url += ( "model=" + getRefference( "choosenModel" ).innerHTML + "&" );
	
	if ( getRefference( "choosenMake" ) != null )
		url += ( "make=" + getRefference( "choosenMake" ).innerHTML + "&" );
	
	if ( getRefference( "choosenFuelType" ) != null )
		url += ( "fueltype=" + getRefference( "choosenFuelType" ).innerHTML + "&" );
	
	if ( getRefference( "choosenTrim" ) != null )
		url += ( "trim=" + getRefference( "choosenTrim" ).innerHTML + "&" );
	
	if ( getRefference( "choosenBodyType" ) != null )
		url += ( "bodytype=" + getRefference( "choosenBodyType" ).innerHTML + "&" );
		
	if ( getRefference( "choosenColor" ) != null )
		url += ( "color=" + getRefference( "choosenColor" ).innerHTML + "&" );
	
	if ( getRefference( "choosenPower" ) != null )
		url += ( "power" + getRefference( "choosenPower" ).innerHTML + "&" );
	
	if ( getRefference( "choosenTransmission" ) != null )
		url += ( "transmission=" + getRefference( "choosenTransmission" ).innerHTML + "&" );
	
	if ( getRefference( "choosenZIP" ) != null )
		url += ( "zip=" + getRefference( "choosenZIP" ).innerHTML + "&" );
	
	if ( getRefference( "selPriceFrom" ).value != "any" && getRefference( "selPriceTo" ).value != "any" )
		url += ( "price=" + getRefference( "selPriceFrom" ).value + "-" + getRefference( "selPriceTo" ).value + "&" );
	else {
		if ( getRefference( "selPriceFrom" ).value != "any" && getRefference( "selPriceTo" ).value == "any" )
			url += ( "price=" + getRefference( "selPriceFrom" ).value + "&" );
		if ( getRefference( "selPriceFrom" ).value == "any" && getRefference( "selPriceTo" ).value != "any" )
			url += ( "price=0-" + getRefference( "selPriceTo" ).value + "&" );
	}
	
	if ( getRefference( "selMileageFrom" ).value != "any" && getRefference( "selMileageTo" ).value != "any" )
		url += ( "mileage=" + getRefference( "selMileageFrom" ).value + "-" + getRefference( "selMileageTo" ).value + "&" );
	else {
		if ( getRefference( "selMileageFrom" ).value != "any" && getRefference( "selMileageTo" ).value == "any" )
			url += ( "mileage=" + getRefference( "selMileageFrom" ).value + "&" );
		if ( getRefference( "selMileageFrom" ).value == "any" && getRefference( "selMileageTo" ).value != "any" )
			url += ( "mileage=0-" + getRefference( "selMileageTo" ).value + "&" );
	}
	
	if ( getRefference( "selYearFrom" ).value != "any" && getRefference( "selYearTo" ).value != "any" )
		url += ( "year=" + getRefference( "selYearFrom" ).value + "-" + getRefference( "selYearTo" ).value + "&" );
	else {
		if ( getRefference( "selYearFrom" ).value != "any" && getRefference( "selYearTo" ).value == "any" )
			url += ( "year=" + getRefference( "selYearFrom" ).value + "&" );
		if ( getRefference( "selYearFrom" ).value == "any" && getRefference( "selYearTo" ).value != "any" )
			url += ( "year=1910-" + getRefference( "selYearTo" ).value + "&" );
	}
	
	url = url.trim().replace( / /g , "+" );
	
	return url.substring( 0 , url.length - 1 );
}


function updateCounter() {
	
	var xmlhttp;
	// start count down animation
	var intervalID = setInterval( "countDown()" , 50 );
	
	if ( window.XMLHttpRequest ) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
	}
	xmlhttp.onreadystatechange = function() {
		if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
			// stopping count down
			clearInterval( intervalID );
			// getting new counter value
			var counter = xmlhttp.responseText.trim().replace( /\./g , '' );
			// clearing previous content
			clearContent( "odometer" );
			// setting new number in odometer
			for ( i = 0; i < counter.length; i++ )
				appendElement( "odometer" , createElementWithAttributes( "span" , { "id" : "od" + ( counter.length - i ) , "innerHTML" : counter.substr( i , 1 ) } ) );
		}
	};
	xmlhttp.open( "GET" , "/QSCounting.ajax?" + getResultAjaxURLCounterParameters() , true );
	xmlhttp.send( null );
}

function zipSubmit(e) {
	var keyCode = (window.event) ? event.keyCode : e.keyCode;
	
	if ( keyCode == 13 ) {
		submitQuickSearch();
	}
}

//function doAjax(url,async){
//	var response = "";
//	var url = "";
//        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
//            // Safari
//            xmlhttpML = new XMLHttpRequest();
//        } else {// code for IE6, IE5
//            xmlhttpML = new ActiveXObject("Microsoft.XMLHTTP");
//        }
//        xmlhttpML.onreadystatechange = function() {
//            if (xmlhttpML.readyState == 4 && xmlhttpML.status == 200) {
//                 response = decodeURI(xmlhttpML.responseText);
//                 return response;
//            }
//        };
//        xmlhttpML.open("GET", url, async);
//        xmlhttpML.send( null );
//}