/*	mobileSearch.js	*/
/* not yet final, not yet unobstrusive */

/*******************************************************************************
 * JD: almost taken "as is" from pre-redesign. TODO: Needs refactoring!
 * Refactoring in progress...
 ******************************************************************************/

// requires FormHelper
if (!mobile || !mobile.FormHelper) {
	// console.error("Missing required dependency: FormHelper");
}

// JD: FIXME - sets field value for given form ('searchForm') by name
function setField(field, value) {
	document.forms['searchForm'].elements[field].value = value;
}

function checkCountriesConsistence(countryCheckbox) {
	if (countryCheckbox.value == '') {
		if (countryCheckbox.checked == true) {
			var allCheckboxes = $$('input');
			for ( var i = 0; i < allCheckboxes.length; i++) {
				if (allCheckboxes[i].className == 'countriesSelector') {
					allCheckboxes[i].checked = false;
				}
			}
		}
	} else if (countryCheckbox.checked == true) {
		// a country checkbox is activated
		$("countriesWorldWide").checked = false;
	} else if (countryCheckbox.checked == false) {
		var countriesSelected = false;
		var allCheckboxes = $$('input.countriesSelector');
		for ( var i = 0; i < allCheckboxes.length; i++) {
			if (allCheckboxes[i].checked == true) {
				countriesSelected = true;
			}
		}
		if (countriesSelected == false) {
			$("countriesWorldWide").checked = true;
		}
	}
}

/* DEPRECATED! */
/* ---- *carSearch.ftl: search by bodystyle ---- */
function uncheckBodyStyle() {
	for ( var i = 0; i < 8; i++) {
		document.forms['searchForm'].categories[i].checked = false;
	}
}

/* DEPRECATED! */
function checkBodyStyleStatus() { // onload
	for ( var i = 0; i < 8; i++) {
		if (document.forms['searchForm'].categories[i].checked == true) {
			if (document.forms['searchForm'].bodyStyleRadioSelect) {
				document.forms['searchForm'].bodyStyleRadioSelect.checked = true;
				document.forms['searchForm'].bodyStyleRadioAll.checked = false;
				makeRadiobuttonActive('bodyStyleInput2', 'bodyStyleInput1');
				break;
			}
		} else {
			setBodyStyleRadioAll();
		}
	}
}

/* DEPRECATED! */
function setBodyStyleRadioAll() {
	if (document.forms['searchForm'].bodyStyleRadioAll) {
		document.forms['searchForm'].bodyStyleRadioAll.checked = true;
		makeRadiobuttonActive('bodyStyleInput1', 'bodyStyleInput2');
	}

}

/* DEPRECATED! */
function makeRadiobuttonActive(id1, id2) {
	if ($(id1) && $(id2)) {
		$(id1).style.fontWeight = "bold";
		$(id2).style.fontWeight = "normal";
	}

}
/* ---- /carSearch.ftl: search by bodystyle ---- */


// TODO
// popUps for search parameters
// basically the same script as the checkLinks function in mobile.js
// when applications are being merged this should be put into mobile.js

function checkParameterLinks() {

	$$("a.parameterPopupLandscape").each(function(link) {
		// add an onclick event on the fly to pass the href attribute
		// of the link to our second function, openPopUp
		link.onclick = function() {
			openPopUp(this.getAttribute("href"), 520, 250, 200, 400, 'no',
					'no', 'no', 'no', 'yes', 'yes');
			return false;
		}
	});

	$$("a.parameterPopupSmall").each(function(link) {
		// add an onclick event on the fly to pass the href attribute
		// of the link to our second function, openPopUp
		link.onclick = function() {
			openPopUp(this.getAttribute("href"), 200, 200, 200, 400, 'no',
					'no', 'no', 'no', 'yes', 'yes');
			return false;
		}
	});

	$$("a.parameterPopupLong").each(function(link) {
		// add an onclick event on the fly to pass the href attribute
		// of the link to our second function, openPopUp
		link.onclick = function() {
			openPopUp(this.getAttribute("href"), 250, 430, 200, 400, 'no',
					'no', 'no', 'no', 'yes', 'yes');
			return false;
		}
	});
	
}
document.observe("mobile:ready", checkParameterLinks);

/* /Scripts search 20 */

function showHideExtended(id, txtId, val1, val2) {
	if (document.getElementById(id).style.display == "none") {
		document.getElementById(txtId).firstChild.nodeValue = val2;
		document.getElementById(id).style.display = "block";
	} else {
		document.getElementById(txtId).firstChild.nodeValue = val1;
		document.getElementById(id).style.display = "none";
	}
}


/* ---- * DES: swap image ---- */
function preloadImages() { // v3.0
	var d = document;
	if (d.images) {
		if (!d.p)
			d.p = new Array();
		var i, j = d.p.length, a = preloadImages.arguments;
		for (i = 0; i < a.length; i++)
			if (a[i].indexOf("#") != 0) {
				d.p[j] = new Image;
				d.p[j++].src = a[i];
			}
	}
}

function findObj(n, d) { // v4.0
	var p, i, x;
	if (!d)
		d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0, p);
	}
	if (!(x = d[n]) && d.all)
		x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++)
		x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++)
		x = findObj(n, d.layers[i].document);
	if (!x && document.getElementById)
		x = document.getElementById(n);
	return x;
}
function swapImage() { // v3.0
	var i, j = 0, x, a = swapImage.arguments;
	document.sr = new Array;
	for (i = 0; i < (a.length - 2); i += 3)
		if ((x = findObj(a[i])) != null) {
			document.sr[j++] = x;
			if (!x.oSrc)
				x.oSrc = x.src;
			x.src = a[i + 2];
		}
}

function swapImgRestore() { // v3.0
	var i, x, a = document.sr;
	for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
		x.src = x.oSrc;
}
/* ---- / DES: swap image ---- */

/* ---- / DES: send contact mail to seller ---- */
function sendMail(contactFormId) {
	new Ajax.Request('sendContactForm.html', {
		asynchronous :false,
		method :'post',
		parameters :Form.serialize('contactForm' + contactFormId),
		onSuccess : function(request) {
			$('contactFormDiv' + contactFormId).update(request.responseText);
		},
		onFailure: function(request){
			$('contactFormDiv' + contactFormId).update(request.responseText);
		}
	
	
	});
}

function reloadCaptcha(div, url) {
	$(div).src=url+'?r='+Math.random();
}

function highlightCounter(element) {
	/* $(id).style.backgroundColor = "#ff6600"; */
	$(element).setStyle( {
		color :"#fafafa"
	});
}
function delightCounter(element) {
	/* $(id).style.backgroundColor = "transparent"; */
	$(element).setStyle( {
		color :""
	});
}

var lastHits = '';

var t;
function requestHitsWithDelayForUrl(hitCounterUrl) {
	if (t) {
		window.clearTimeout(t)
	}
	t = window.setTimeout("requestHitsForUrl('" + hitCounterUrl + "')", 500);
}

/* FIXME: the following number formatting does not respect locales */

/**
 * Print the hit counter to the hits counter box and all relevant submit
 * "buttons".
 * 
 * param hits : (string) either a simple number or two numbers separated by a
 * comma, in which case
 * 
 * JD: refactored to use regexps and replace contents of elements with class
 * "hitCounter"/"extHitCounter" instead of explicit ids.
 */
function printHits(hitsWithExtended) {

	// TODO: There is a bug somewhere calling this method without parameter.
	if (undefined === hitsWithExtended || undefined === hitsWithExtended.hitsCount) {
		// console.warn("printHits called with null parameter!");
		return;
	}	
    var hits = hitsWithExtended.hitsCount;
    
	// if we received more than one hit counters then
	// the second one is the count for the international search.
	var isExtensionHitscounter = ! ( (undefined === hitsWithExtended.localMarketplaceHitsCount) &&
	                                 (undefined === hitsWithExtended.internationalHitsCount ));
	
	if (isExtensionHitscounter) {
	    //either international or local hit count expected to exist
	    isInternational= !Object.isUndefined(hitsWithExtended.internationalHitsCount);
	    //bug fixing: 2 HitCouters are on the page for IE6 (with the same ids)
	    if (mobile.BrowserCheck.IE6){
	    	$('fixedHitCounter').remove();
	    }
	    if (isInternational) {
	    		$('extensionHitCounterLocalMarketplace').hide();
	    		$('extensionHitCounterInternationalMarketplace').show();
		} else {
			    $('extensionHitCounterInternationalMarketplace').hide();
			    $('extensionHitCounterLocalMarketplace').show();
		}
		var extHitCounters = $$('.extHitCounter');
		extHitCounters.each( function(extCounter) {
			var extHits = isInternational ? hitsWithExtended.internationalHitsCount : hitsWithExtended.localMarketplaceHitsCount;
			extCounter.update(extHits);
			highlightCounter(extCounter);
			window.setTimeout(delightCounter.curry(extCounter), 150);
		});
	}

	// update buttons and show ": " before numbers.
	$$('.hitCounter').each( function(counter) {
		counter.update(hits);
		var button = counter.up('.button');
		if (button)
			button.removeClassName('empty');
		highlightCounter(counter);
		window.setTimeout(delightCounter.curry(counter), 150);
	});
}

function formatHitsCount(count) {
	var thousandSeparator;	// will be part of regular expression, escape if needed (double).
	switch (language) {
		case "en":
			thousandSeparator = ",";
			break;
		case "fr":
			thousandSeparator = " ";
			break;
		default:
			thousandSeparator = "\\.";
	}

	var re = new RegExp("(\\d)(\\d{3})($|" + thousandSeparator + ")");

	while (re.test(count))
		count = count.replace(re, "$1.$2$3");

    return count;
}

function requestHitsForUrl(url) {
	
	//GET params
	var params = {};
	
	//parameters removed from GET Request 
	//get params on search-form and search-result pages should be equal to enable browser caching 
	var removedParams = ["__lp", "_features", "bodyStyleRadio", "segment", "siteId", "vehicleCategory", "negativeFeatures"];
	
	//serialize search form, sort and strip empty fields
	var serializedForm = $H(Form.serialize('searchForm', true));
	serializedForm.keys().sort().each(function(key){
		
		var stripParam = true;
		
		if(removedParams.indexOf(key) == -1 && serializedForm.get(key)!==""){
			//remove empty power arrays
			if(key=="maxPowerAsArray" || key=="minPowerAsArray"){
				if(serializedForm.get(key)[0]!="") stripParam=false;
			}
			//remove searchInFreetext if false
			else if (key.indexOf(".searchInFreetext") > -1){
				if (serializedForm.get(key) == "true") stripParam=false;
			} 
			else stripParam=false;
		}
		if(!stripParam) this[key] = serializedForm.get(key);
		
	}, params);
	
	//make request
	new Ajax.Request(url, {
		method :'get',
		parameters :params,
		onSuccess : function(request) {
			var hits = request.responseText.evalJSON();
			lastHits = hits;
			printHits(hits, false);
		}
	});
}

function requestExtendedHitsForUrl(url) {

	var params = Form.serialize('searchForm', true);

	params['lang'] = ''; // unset lang to enable language independent caching

	if (typeof params['siteIds'] != "string") {
		$('extensionHitsCounterBox').hide();
		return;
	}

	$('extensionHitsCounterBox').show();

	params['countries'] = "ALL_EUROPE";

	new Ajax.Request(url, {
		method :'get',
		parameters :params,
		onSuccess : function(request) {
			var hits = request.responseText.evalJSON();
			lastHits = hits;
			printHits(hits, true);
		}
	});
}

var extendedT;
function requestExtendedHitsWithDelayForUrl(hitCounterUrl) {
	if (extendedT) {
		window.clearTimeout(extendedT)
	}
	extendedT = window.setTimeout("requestExtendedHitsForUrl('" + hitCounterUrl + "')", 500);
}

/**
 * Submit the extended search :
 *  -> manipulate the country selection to "", so that the search request will
 * not include countries; and the zip code to "".
 *  -> and submit.
 * 
 * @return
 */
function submitSearchForExtendedHits() {
	var countrySelect = $("ambitCountry");
	// store the current value and change it.

	if (countrySelect.options) { // <select>
	    if (document.getElementById('extensionHitCounterLocalMarketplace').style.display != "none") { //local
		    for ( var i = 0; i < countrySelect.options.length; i++) {
			    if (countrySelect.options[i].value == mobile.defaultCountry) {
				    countrySelect.options[i].selected = true;
				    break;
			    }
		    }
	    } else if (document.getElementById('extensionHitCounterInternationalMarketplace').style.display != "none") { //international
		    country = countrySelect.selectedIndex;
		    countrySelect.selectedIndex = 0;
	    }
	} else { // <input type="hidden">
	    if (document.getElementById('extensionHitCounterLocalMarketplace').style.display != "none") { //local
            countrySelect.value=mobile.defaultCountry;
	    } else if (document.getElementById('extensionHitCounterInternationalMarketplace').style.display != "none") { //international
    		country = countrySelect.value;
		    countrySelect.value = "";
	    }
	}

	var zipInput = $("zipcode");
	zipInput.value = "";
	
	var zipcodeRadius = $("zipcodeRadius");
	zipcodeRadius.value = "";

	var radiusInput = $("zipcodeRadius");
	if (radiusInput)
		radiusInput.disable();
    		
	// submit the form.

	document.forms['searchForm'].submit();

}

/* makeModelVarian */
/* used in buyer-webapp and buyer-search-webapp */
/* this retrieves the models asynchronously */

function retrieveModelsForAllMakeSelections() {
	$R(1, 3).each( function(i) {
		// invoked 3 times for i = 1 to 3
			try {
				var selectedMake = $F("selectMake" + i);
				if (selectedMake != "") {
					var selectedModel = $F('selectModel' + i);
					retrieveModels(selectedMake, i, true, selectedModel);
				}
			} catch (e) {
			}
		});
}

function retrieveModels(selectedMake, makeModelVariantIndex, keepModelSelection, modelValue) {
	if (makeModelVariantIndex == undefined) {
		makeModelVariantIndex = '';
	}

	var makeId = selectedMake;
	if (makeId == '') {
		// disable model list if no make is selected
		_updateModelSelect(makeModelVariantIndex, "", true);
		mobile.FormHelper.disableFieldAndLabel('selectModel' + makeModelVariantIndex);
		return;
	}

	// enable other fields in row + make selection of next row!
	mobile.FormHelper.enableFieldAndLabel('selectModel' + makeModelVariantIndex);

	// add parameters....

	// makeId
	var params = 'makeId=' + makeId;

	if (document.searchForm.categories != null) {

		if (document.searchForm.categories.type == "select-one") {
			if (document.searchForm.categories.value != "") {
				params += "&categories=" + document.searchForm.categories.value;
			}
		} else {
			params += '&' + Form.serializeElements(document.searchForm.select('input[name=categories]'));
		}
	}

	var contextPath = extractContextPath(document.searchForm.action);
	var prospectiveURI = (contextPath && contextPath != "") ? contextPath + "/models.html" : "models.html";
	var prospectiveURIParts = parseUri(prospectiveURI);
	var currentURI = document.location.href;
	var currentURIParts = parseUri(currentURI);

	// see MBL-9743
	var requestURI = (isAbsoluteURI(prospectiveURI) && prospectiveURIParts["domain"] != currentURIParts["domain"]) ? requestURI = currentURIParts["protocol"]
			+ "://"
			+ currentURIParts["domain"]
			+ (currentURIParts["port"] ? ":" + currentURIParts["port"] : "")
			+ currentURIParts["directoryPath"]
			+ prospectiveURIParts["fileName"]
			: requestURI = prospectiveURI;

	params += '&lang=' + language;
	
	new Ajax.Request(
			requestURI,
			{
				method :'get',
				parameters :params,
				onSuccess : function(request) {
					var modelSelection = _updateModelSelect(makeModelVariantIndex, request.responseText);

					if (keepModelSelection) {
						if (modelValue) {
							var modelOptions = $A($('selectModel' + makeModelVariantIndex).options);
							var option = modelOptions.find(function(option) {
								return option.value == modelValue;
							});
							if (option) {
								option.selected = true;
							}
						}
					}
				}
			});
}

/**
 * Returns the HTML representing an model selection select element.
 * @param index The running number of the model select field, will be attached to the DOM id. On the DSS usually 1..3. Defaults to ''.
 * @param content Options as HTML. Defaults to '' (no options).
 * @return HTML string representing a model selection select field.
 */
function _createModelSelectHTML(index, content) {
	if (index == undefined) {
		index = -1;
	}
	return '<select class="modelSelection"'
		+ ' id="selectModel' + index + '"'
		// Name property of select field will be prefixed with makeModelVariant + index if an index is given.
		// Leave index param empty for a single model field. (JD)
		+ ' name="' + (index > 0 ? 'makeModelVariant' + index + '.' : '') + 'modelId">'
		+ (content || '')
		+ '</select>';
}

/**
 * Updates a model selection select element with the given options.
 * @param index The running number of the model select field. On the DSS usually 1..3. Defaults to ''.
 * @param content The select field options as HTML.
 * @param keepDefaultOption If this parameter is set to true, the default option (with value="") will be kept.
 */
function _updateModelSelect(index, content, keepDefaultOption) {
	if (index == undefined) {
		index = '';
	}
	
	var parent = $('modelSelection' + index);
	if (parent) {
		var selectElement = parent.down('select');

		// Construct default option, if needed.
		if (keepDefaultOption) {
			var defaultOptionElement = selectElement.down('option[value=""]');
			if (defaultOptionElement) {
				// construct a new default option (we have no outerHTML in FF) and prepend to content.
				var newDefaultOptionHTML = "<option value=''>" + defaultOptionElement.innerHTML + "</option>";
				content = newDefaultOptionHTML + content;
			}
		}
		
		// Update select element.
		// In IE we replace the full parent select element to avoid some problems.
		// FF works just fine with innerHTML update.
		if (Prototype.Browser.IE) {
			// TODO: stop observing before updating?
			parent.update(_createModelSelectHTML(index, content));
			// In IE, notify of DOM change to attach new handlers etc.
			parent.fire("dom:update", parent);
		} else {
			selectElement.update(content);
		}
	}
}

function enableModelSelection(index) {
	var element = $('selectModel' + index);
	if (element) {
		element.disable();
	}
}

function disableModelSelection(index) {
	var element = $('selectModel' + index);
	if (element) {
		element.disable();
		element.value = "";
	}
}

var numberOfMakeModels = 3;

function loadModelSelection() {
	var loaded = false;

	var state = loadState();

	if (state != null) {
		var values = state.split('_');
		for ( var i = 1; i <= numberOfMakeModels; i++) {
			if ($('selectMake' + i)	&& $F('selectMake' + i) != '') {
				retrieveModels($F('selectMake' + i), i, true, values[i - 1]);
				loaded = true;
			}
		}
		if (loaded) {
			lastHits = values[3];
			if (lastHits != '') {
				printHits(lastHits);
			}
		} else {
			requestHits();
		}
	}

}

function saveModelSelection() {
	var cValue = '';
	for ( var i = 1; i <= numberOfMakeModels; i++) {
		if ($('selectModel' + i) != null) {
			cValue = cValue.concat($('selectModel' + i).getValue());
			cValue = cValue.concat('_');
		}
	}
	cValue = cValue.concat(lastHits);

	saveState(cValue);
}

function parkCompare(parkOrCompare) {

	var paramName = '';
	if (parkOrCompare == 'park') {
		paramName = "adIdToPark"
	} else {
		paramName = 'adIds';
	}

	var idParams = '';

	var checkedItems = 0;
	if (document.parkAndCompareVehicle.parkAndCompare.length) {
		for ( var i = 0; i < document.parkAndCompareVehicle.parkAndCompare.length; i++) {
			var item = document.parkAndCompareVehicle.parkAndCompare[i];

			if (item.checked == true) {
				idParams += paramName + '=' + item.value + '&';
				checkedItems++;
			}

		}
	} else if (document.parkAndCompareVehicle.parkAndCompare) {
		var item = document.parkAndCompareVehicle.parkAndCompare;
		if (item.checked == true) {
			idParams += paramName + '=' + item.value + '&';
			checkedItems++;
		}
	}

	// alert(idParams);

	if (parkOrCompare == 'park' && idParams != '') {
		location = parkingUrl + '?lang=' + language + '&' + idParams;
	} else if (parkOrCompare == 'compare' && idParams != '') {
		window.open(vehicleComparisonUrl + '?' + idParams, 'FzgVergleich', 'width=950,height=720,left=0,top=0,resizable=yes,scrollbars=yes');
	}

	return false;

}
// use id quicksearch for prefilling the detail search mask
function submitQuickSearch(go2searchMask) {
	var searchForm = document.forms["searchForm"];
	if (go2searchMask) {
		searchForm.isSearchRequest.disabled = true;
		searchForm.editSearch.disabled = false;
		searchForm.editSearch.value = 1;
	} else {
		searchForm.editSearch.disabled = true;
		searchForm.isSearchRequest.disabled = false;
		searchForm.isSearchRequest.value = "true";
	}
	if (searchForm.zipcodeRadius != null
			&& searchForm.zipcodeRadius.value != "") {
		searchForm.ambitCountry.value = "DE";
	}
	searchForm.submit();
}

function changeHiddenSortByField(searchFieldName) {
	$('sortBy').value = searchFieldName;
}

function changeHiddenExportSortByField(element, grossSearchFieldName, NetSearchFieldName){
	var sortByField = $('sortBy');
	if (sortByField == null) {
		sortByField = $$('#searchForm input[name="sortOption.sortBy"]')[0];
	}
	
	if (element.value == 'ALSO_EXPORT' || element.value == 'ONLY_EXPORT') {
		sortByField.value = NetSearchFieldName;
	} else {
        sortByField.value = grossSearchFieldName;
	}
}

function changePriceSortBySelectOption(priceSearchFieldName) {
	// price option is the first option in the selection list!!!!!
	$('sortBy').options[0].value = priceSearchFieldName;
}

function loadRecommendations(url) {
	new Ajax.Request(url, {
		method :'get',
		onSuccess : function(request) {
			var r = String(request.responseText);
			if (r.length > 2) {
				$('contentBoxRecommendations').update(r);
			}

		}
	});
}

/* loads sponsored ads in one row of the search result list, 
 * triggered with onload from searchresultsTopInCategory.ftl */
function loadTopInCategory(url) {
	//the table row only exists when searchCommand.availableTopInCategoryAds > 0
	var sponsoredRow = documentBody.down('tr.sponsored td');
	
	if (sponsoredRow){
		
	new Ajax.Request(url, {
		method :'get',
		onSuccess : function(request) {
			var r = String(request.responseText);
			if (r.indexOf("sponsored-wrapper") > -1) {
					sponsoredRow.update(r);
					
					//need some styles here
					//background
					sponsoredRow.setStyle({backgroundColor: "#FF691F"});
					//noborder for the next row
					sponsoredRow.up("tr").next("tr").addClassName("noborder");
					
					//hover for ie6
					if (Prototype.Browser.IE && typeof document.body.style.maxHeight == "undefined") {
						var sponsoredWrapper = documentBody.down(".sponsored-wrapper");
						
						sponsoredWrapper.select("dl").invoke("observe" ,"mouseenter", (function(event){
							var element = Event.findElement(event, "dl");
							element.down("dd.details").setStyle({visibility: "visible"});
						}).bindAsEventListener());
		
						sponsoredWrapper.select("dl").invoke("observe" ,"mouseleave", (function(event){
							var element = Event.findElement(event, "dl");
							element.down("dd.details").setStyle({visibility: "hidden"});
						}).bindAsEventListener());
					}
			}
			
		}
	});
}
}

function changeSortOrder(searchField) {
	if (searchField == "creationTime" || searchField == "specifics.firstRegistration") {
		$("sortOrder").value = "DESCENDING";
	} else {
		$("sortOrder").value = "ASCENDING";
	}
}

function changeDefaultOrder(searchField) {
	if (searchField == "creationTime"
			|| searchField == "specifics.firstRegistration") {
		$("defaultOrder").value = "DESCENDING";
	} else {
		$("defaultOrder").value = "ASCENDING";
	}
	return true;
}

function setPowerUnit() {
	$('minPowerUnit').value = $('powerUnit').value;
	$('maxPowerUnit').value = $('powerUnit').value;
}

function switchToExportSearch() {
	if ($("formForSearch").negativeFeatures.value == 'EXPORT') {
		$("formForSearch").negativeFeatures.value = "";
	}
	$("formForSearch").isSearchRequest.disabled = true;

	var formActionURL = $("formForSearch").action;
	var switchUrl = formActionURL + "?editSearch=1&switchRandom="
			+ Math.random() + "&" + $('formForSearch').serialize();
	location.href = switchUrl;
}

function extractContextPath(path) {
	if (!path || path == "")
		return "";

	var re = /(.+)\/[^\.\/]*.html/;
	re.ignoreCase;
	if (!re.exec(path))
		return "";

	return RegExp.$1;
}

// parseUri JS v0.1.1, by Steven Levithan <http://stevenlevithan.com>
function parseUri(sourceUri) {
	var uriPartNames = [ "source", "protocol", "authority", "domain", "port",
			"path", "directoryPath", "fileName", "query", "anchor" ], uriParts = new RegExp(
			"^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?")
			.exec(sourceUri), uri = {};

	for ( var i = 0; i < 10; i++) {
		uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
	}

	/*
	 * Always end directoryPath with a trailing backslash if a path was present
	 * in the source URI Note that a trailing backslash is NOT automatically
	 * inserted within or appended to the "path" key
	 */
	if (uri.directoryPath.length > 0) {
		uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
	}

	return uri;
}

function isAbsoluteURI(uri) {
	var uriParts = parseUri(uri);
	return (uriParts["protocol"] && uriParts["protocol"] != ""
			&& uriParts["domain"] && uriParts["domain"] != "");
}
