//funkcija za trim stringa
String.prototype.trim = function()
{ return this.replace(/^\s+|\s+$/g, ''); }

// funkcija startsWith za string
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

// funkcija endsWith za string
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

//creates an XMLHttpRequest instance
function createXMLHttpRequestObject()
{
  // xmlHttp will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // try to instantiate the native XMLHttpRequest object
  try
  {
    // create an XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    }
    catch(e) { }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

function fill_covered (label)
{
	fill_selected(document.getElementById ("min_covered"), label, 5000, 150001, new Array (10000, 100000), new Array (5000, 10000, 25000), "", "", "null", "");
	fill_selected(document.getElementById ("max_covered"), label, 5000, 150001, new Array (10000, 100000), new Array (5000, 10000, 25000), "150.000+", "more", "null", "");
}

function fill_year (label)
{
	fill_selected_year(document.getElementById ("min_year"), label, 2009, 1990, -1, "1990-", "less", "null", "");
	fill_selected_year(document.getElementById ("max_year"), label, 2009, 1990, -1, "", "", "null", "");
}

function fill_price (label)
{
	fill_selected(document.getElementById ("min_price"), label, 500, 60001, new Array (1000, 15000, 30000), new Array (500, 1000, 2500, 5000), "", "", "null", "");
	fill_selected(document.getElementById ("max_price"), label, 500, 60001, new Array (1000, 15000, 30000), new Array (500, 1000, 2500, 5000), "60.000+", "more", "null", "");
}

function checkParkedCars (unparkText)
{
	var cookie = document.cookie;
	
	var arr = cookie.split("ooyyo=");
	
	if (arr[1] == null)
		return;
	
	if (arr[1].indexOf ("\"") != -1)
	{
		var cars = arr[1].substring (1, arr[1].length - 1).split(",");
		
		for (car in cars)
		{
			var btn = document.getElementById ("park" + cars[car]);
			
			if (btn != null)
			{
				btn.value = unparkText;
				btn.className = 'nopark';
			}
		}
	}
	else
	{
		var btn = document.getElementById ("park" + arr[1]);
		
		if (btn != null)
			btn.value = unparkText;
	}
}

var includeTrimWithoutLabel = "";

function on_load_func (anyLabel, unparkText, trimDeServer)
{
	fill_covered(anyLabel);
	fill_year(anyLabel);
	fill_price(anyLabel);
	
	checkParkedCars (unparkText);
	
	includeTrimWithoutLabel = trimDeServer;
}

/** COMBOBOXES */

function set_covered (field, label, from, to, maxLabel, maxVal)
{
	var selObj = document.getElementById (field);
	var selOpt = selObj.options[selObj.selectedIndex].value;
	
	var remove = "";
	if (field.indexOf ("max_") != -1)
		remove = "first";
	
	var fromInt = parseInt(from);
	var toInt = parseInt (to);
	
	if (isNaN(fromInt))
	{
		fromInt = 0;
		remove = "";
	}
	
	if (isNaN(toInt))
		toInt = 150001;
	
	var borders = new Array (10000, 100000);
	var steps = new Array (5000, 10000, 25000);
	
	if (selOpt != "null" && selOpt != "more")
		fill_selected(selObj, label, fromInt, toInt, borders, steps, maxLabel, maxVal, parseInt(selOpt), remove);
	else
		fill_selected(selObj, label, fromInt, toInt, borders, steps, maxLabel, maxVal, selOpt, remove);
	
	
	var submit = document.getElementById ("covered_submit");
	
	if (checkRange(field.substr (4)) === "less-more")
		submit.style.display = "none";
	else if (submit.style.display === "none")
		submit.style.display = "block";
}

function set_price (field, label, from, to, maxLabel, maxVal)
{
	var selObj = document.getElementById (field);
	var selOpt = selObj.options[selObj.selectedIndex].value;
	
	var remove = "";
	if (field.indexOf ("max_") != -1)
		remove = "first";
	
	if (field.indexOf ("min_") != -1)
		maxLabel = "";
	
	var fromInt = parseInt(from);
	var toInt = parseInt (to);
	
	if (isNaN(fromInt))
	{
		fromInt = 0;
		remove = "";
	}
	
	if (isNaN(toInt))
		toInt = 60001;
	
	var borders = new Array (1000, 15000, 30000);
	var steps = new Array (500, 1000, 2500, 5000);
	
	if (selOpt != "null" && selOpt != "more")
		fill_selected(selObj, label, fromInt, toInt, borders, steps, maxLabel, maxVal, parseInt(selOpt), remove);
	else
		fill_selected(selObj, label, fromInt, toInt, borders, steps, maxLabel, maxVal, selOpt, remove);
	
	var submit = document.getElementById ("price_submit");
	
	if (checkRange(field.substr (4)) === "less-more")
		submit.style.display = "none";
	else if (submit.style.display === "none")
		submit.style.display = "block";
}

function set_year (field, label, from, to, maxLabel, maxVal)
{
	var selObj = document.getElementById (field);
	var selOpt = selObj.options[selObj.selectedIndex].value;
	
	var fromInt = parseInt(from);
	var toInt = parseInt (to);
	if (isNaN(fromInt))
	{
		fromInt = 2009;
		remove = "";
	}
	
	if (isNaN(toInt))
		toInt = 1990;
	
	if (selOpt != "null" && selOpt != "more")
		fill_selected_year(selObj, label, fromInt, toInt, -1, maxLabel, maxVal, parseInt(selOpt));
	else
		fill_selected_year(selObj, label, fromInt, toInt, -1, maxLabel, maxVal, selOpt);
	
	var submit = document.getElementById ("year_submit");
	
	if (checkRange(field.substr (4)) === "less-more")
		submit.style.display = "none";
	else if (submit.style.display === "none")
		submit.style.display = "block";
}

function fill_selected_year (sel, firstEl, from, to, step, maxLabel, maxVal, selected)
{
	if (sel == null)
		return;
	// prazni combobox i postavlja prvu opciju
	sel.options.length = 0;
	sel.options[0] = new Option (firstEl, "null");
	sel.selectedIndex = 0;
	
	var counter = 1;
	for (var i = parseInt(from); i >= parseInt(to); i += step)
	{
		var option = new Option (i, i);
		sel.options[counter] = option;
		
		if (option.value == selected)
			sel.selectedIndex = counter;
				
		counter++;
	}
	
	if (maxLabel != "")
	{
		var option = new Option (maxLabel, maxVal);
		sel.options[counter] = option;
		
		if (maxVal === selected)
			sel.selectedIndex = counter;
	}
}

function fill_selected (sel, firstEl, from, to, borders, steps, maxLabel, maxVal, selected, remove)
{
	if (sel == null)
		return;
	// prazni combobox
	sel.options.length = 0;
	
	sel.options[0] = new Option (firstEl, "null");
	sel.selectedIndex = 0;
	
	var stepCounter = 0;
	for (i = 0; i < borders.length; i++)
	{
		if (from > borders[i])
			stepCounter = i + 1;
	}
	var border = borders[stepCounter];
	var step = steps[stepCounter];
	
	var counter = 1;
	
	for (var i = parseInt(from); i < parseInt(to); i += step)
	{
		var option = new Option (addDelimiter (i), i);
		sel.options[counter] = option;
		
		if (option.value == selected)
			sel.selectedIndex = counter;
		
		if (i >= border)
		{
			stepCounter++;
			step = steps[stepCounter];
			border = borders[stepCounter];
		}
				
		counter++;
	}
	
	if (maxLabel != "")
	{
		var option = new Option (maxLabel, maxVal);
		sel.options[counter] = option;
		
		if (maxVal === selected)
			sel.selectedIndex = counter;
	}
	
	if (remove != "")
	{
		if (remove === "first")
			sel.remove (1);
	}
}

function addDelimiter (nStr)
{
	var delimiter = ".";
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + delimiter + '$2');
	}
	return x1 + x2;
}

function checkRange (field)
{
	// uzima kontrolu comboboxa
	var minObj = document.getElementById ("min_" + field);
	var maxObj = document.getElementById ("max_" + field);
	
	// uzima vrednost slektovane opcije
	var minVal = minObj.options[minObj.selectedIndex].value;
	var maxVal = maxObj.options[maxObj.selectedIndex].value;
	
	return minVal.replace("null", "less") + "-" + maxVal.replace("null", "more");
}

function submitRange (field)
{
	minMax = checkRange (field);
	
	var url = getURL () + "/"+ field + "-" + minMax;
	
	window.location = url;
}

/** END COMBOBOXES */


function item_over (item)
{
	if (item.className == "view_more")
	{
		item.className = "view_more_over";
	}
	else if (item.className != "selected_item")
	{
		item.className = "mouse_over_item";
	}

}

function item_out (item)
{
	if (item.className == "view_more_over")
	{
		item.className = "view_more";
	}
	else if (item.className != "selected_item")
	{
		item.className = "mouse_out_item";
	}
}

// funkcija koja daje url adresu iz adressBar-a bez parametra 'page'
function getURL ()
{
	var url = decodeURI(window.location.href);
	var newUrl = "";
	
	index = url.indexOf("/page-");
	
	if(index != -1)
	{
		newUrl = url.substring (0, url.indexOf ("/page-"));
	}
	else if (url.endsWith ("/"))
		newUrl = url.substr (0, url.length - 1);
	else
		newUrl = url;
	
	return newUrl;
}

function click_related (append, direction)
{
	var url = getURL();
	var index = url.indexOf (direction) + direction.length ();
	
	url = url.substring (0, index) + append;
	
	window.location = url;
}

//promenio sam
function toggle(x, moreLabel, lessLabel, lang, make, model, trim, country, city, direction, rawUrl)
{
	var divx = document.getElementById (x);
	var label = document.getElementById('more_' + x);
	label.innerHTML = "<img src='/images/view-more-loader.gif' alt='loader' />";
	
	var data = "lang=" + lang + "&what=" + x + "&rawUrl=" + rawUrl +  "&by=";
	var newText = "";
	
	if (label.title === "more")
	{
		data += "name";
		newText = "« " + lessLabel;
		label.title = "less";
	}
	else if (label.title === "less")
	{
		data += "count";
		newText = moreLabel + " »";
		label.title = "more";
	}
	
	var params = getURL().split("/" + direction + "/")[1];
	
	if (make != "")
	{
		data += "&make=" + make;
		
		if (model != "")
		{
			data += "&model=" + model;
			
			if (trim != "")
				data += "&trim=" + trim;
		}
	}
	
	if (country != "")
	{
		data += "&country=" + country;
		
		if (city != "")
			data += "&city=" + city;
	}
	
	
	if (params.indexOf ("/") != -1)
	{
		params = params.split("/");
		
		for (i in params)
		{
			var p = params[i];
			
			if ((make != "" && p.indexOf (make) != -1) || 
				(model != "" && p.indexOf (model) != -1) ||
				(trim != "" && p.indexOf (trim) != -1) ||
				(country != "" && p.indexOf (country) != -1) ||  
				(city != "" && p.indexOf (city) != -1))
			{
				continue;
			}
			else
			{
				data += "&" + p.replace(/-/, "=");
			}
		}
	}
	
	// poziva servlet sa parametrima
	var jsUrl = "/SortByFilterServlet?" + data;
	
	var xhr = createXMLHttpRequestObject();
	
	xhr.onreadystatechange = function ()
	{
        if (xhr.readyState == 4)
        {
            if(xhr.status == 200)
            {
            	divx.innerHTML = xhr.responseText;
            	label.innerHTML = newText;
            }
            else
            {
                //console.log("loadAndEval: Load failed!");
            }
        }
    };
    
    xhr.open("GET", jsUrl, true);
    xhr.send(null);
}

function sortBy (by)
{
	var loc = getURL ();
	var url = "";
	
	if (loc.indexOf ("sort-") == -1)
	{
		if (by === "best")
		{
			url = loc;
		}
		else if (by === "covered")
		{
			url = loc + "/sort-covered-asc";
		}
		else if (by === "price")
		{
			url = loc + "/sort-price-asc";
		}
		else if (by === "year")
		{
			url = loc + "/sort-year-asc";
		}
	}
	else
	{
		url = loc.substring (0, loc.indexOf ("sort-"));
		
		if (by == "best")
		{
			window.location = url;
			return;
		}
		
		var byAddr = loc.substring (loc.indexOf ("sort-") + 5, loc.length);
		byAddr = byAddr.substring (0, byAddr.indexOf ("sc") - 1);
		
		if (byAddr.startsWith (by))
		{
			if (loc.indexOf ("-asc") != -1)
			{
				url += "sort-" + by + "-desc";
			}
			else if (loc.indexOf ("-desc") != -1)
			{
				url += "sort-" + by + "-asc";
			}
		}
		else
		{
			url += "sort-" + by + "-asc";
		}
	}
	
	window.location = url;
}

//promenio sam
function tag_clicked (item, make, model, country, city, direction)
{
	var url = getURL ();
	var itemIndex = url.indexOf (item.id.replace (/ /, "+"));
	
	if (item.id === "all")
	{
		url = url.substring(0, url.indexOf (direction) + direction.length + 1) + "/view-bestmatch";
	}
	else
	{
		var index = 0;
		
		if (item.id === make && model != "")
		{
			index = url.indexOf (model.replace (/ /, "+")) - 1;
		}
		else if (item.id === country && city != "")
		{
			index = url.indexOf (city.replace (/ /, "+")) - 1;
		}
		else
		{
			index = url.indexOf ("/", itemIndex);
		}
		
		if (index > 28)
		{
			url = url.substring (0, index);
		}
		else
		{
			return false;
		}
	}
	
	window.location = url;
}

function park(buttonID, carID, parkText, unparkText)
{
    jQuery.get("/ParkServlet",
    	{
        	"cid":carID
    	}, 
    	function(data)
    	{
	        if(data == 'added')
	        {
	            document.getElementById (buttonID).value = unparkText;
	            document.getElementById (buttonID).className = 'nopark';
	        }
	        else if(data == 'removed')
	        {
	        	document.getElementById (buttonID).value = parkText;
	            document.getElementById (buttonID).className = 'park';
	        }
    	});
}