function setCookie(name, value, expires, path, domain, secure)
{

	var cookiestring = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	var cookiestring2 = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") + "; domain=liquic.com;";
	document.cookie= cookiestring;
}

function setCookieNew(name, value, expires, path, domain, secure)
{
	var domain = 'liquic.com';
	document.cookie= name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	"; domain=" + domain +
	((secure) ? "; secure" : "");
}

function setHomepage(wnd, altMessage) {
	if (M) {
		wnd.style.behavior='url(#default#homepage)';
		wnd.setHomePage('http://www.liquic.com/');
	} else {
		alert( altMessage )
	}
}

function setCountryCookie( country_value ) {
	var today = new Date()
	var expires = new Date();
	expires.setTime(today.getTime() + 1000*60*60*24*365);
	setCookie('shb_country', country_value, expires, '/');
}

function changeLanguage( select ) {

	var today = new Date()
	var expires = new Date();
	var strURL = document.URL;

	expires.setTime(today.getTime() + 1000*60*60*24*365);
	setCookie('shb_lang', select.value, expires, '/', '.liquic.com');

	var baseurl;
	var strURL = document.URL;
	var strFile;
	var rest;
	var strURLEN='www.liquic.com';
	var strURLNL = 'nl.liquic.com';
	//if it doesn't have a lang variable in the URL, but it user is switching from a lang to another lang which does not match the domain, then add the lang variable...

	//check domain
	if (strURL.substring(strURL.length-1, strURL.length)=='/') {
		strURL = strURL.substring(0, strURL.length-1);
	}
	//strURL = 'http://www.liquic.com/browsearticles';
	if (strURL.indexOf('www.liquic.com')>0) {
		if ( select.value=='nederlands') {
			//it's .com and changing lang to nederlands, then switch to nl.liquic.com
			baseurl = 'http://nl.liquic.com/';
			rest = strURL.substring(baseurl.length, strURL.length);
		}
		else {
			baseurl = 'http://www.liquic.com/';
			rest = strURL.substring(baseurl.length, strURL.length);
		}

	}

	if (strURL.indexOf('www.liquic.nl')>0 || strURL.indexOf('nl.liquic.com')>0) {

		if (select.value=='english') {
			//it's .nl and changing lang to english,
			baseurl = 'http://www.liquic.com';
			rest = strURL.substring(20, strURL.length);  //I can use 20 since liquic.nl and nl.liquic are both 20
		}
		else {
			baseurl = 'http://nl.liquic.com';
			rest = strURL.substring(20, strURL.length);
		}

	}

	if (baseurl=='') {
		baseurl = 'http://www.liquic.com';
	}

	if (baseurl.substring(baseurl.length-1, baseurl.length)=='/' && rest.substring(0,1)=='/') {
		baseurl = baseurl.substring(0, baseurl.length-1);
	}

	//	strURL = 'http://127.0.0.1/blender/live/video/69/jonny_bowden_gives_his_views_on_the_fad_diets.html';
	//	baseurl = 'http://127.0.0.1/blender/live';
	//	rest = strURL.substring(baseurl.length, strURL.length);
	//	alert(rest);

	//	if (rest.indexOf('/')>0) {
	//			strFile = rest.substr(0, rest.indexOf('/'));
	//			strRest = '/' + rest.substr(strFile.length + 1, rest.length);

	//	}else {
	//		strFile = rest;
	//		strRest = '';
	//	}

	//add the lang you just switched to
	strURL = baseurl + rest;
	//strURL = baseurl + strFile + strRest;
	//	alert(strURL);

	//strURL = baseurl
	window.location = strURL;

	//	location.replace( document.URL );
}
function changeLanguageOld( select ) {
	var today = new Date()
	var expires = new Date();
	var strURL = document.URL;
	expires.setTime(today.getTime() + 1000*60*60*24*365);
	setCookie('shb_lang', select.value, expires, '/');

	if (strURL.indexOf('?')==-1) {
		if (strURL.indexOf('/en/')>0) {

			strURL = strURL.replace('/en', '');
			window.location = strURL;
		}
		else if (strURL.indexOf('/nl/')>0) {
			strURL = strURL.replace('/nl', '')
			window.location = strURL;
		}
		else {

			//if it doesn't have a lang variable in the URL, but it user is switching from a lang to another lang which does not match the domain, then add the lang variable...
			strURL = document.URL;
			//		strURL = 'http://www.liquic.com/';
			//check domain
			//	baseurl = 'http://127.0.0.1/blender/live/';

			if (strURL.indexOf('.com')>0 && select.value=='nederlands') {
				//it's .com and changing lang to nederlands, then add lang var
				baseurl = 'http://www.liquic.com/';
				//	baseurl = 'http://dev.liquic.com/';
				rest = strURL.substring(baseurl.length, strURL.length);
				//if (rest=='/'){rest=''}else {rest=rest};

				if (rest.indexOf('/')>0) {

					strFile = rest.substr(0, rest.indexOf('/'));
					strRest = '/' + rest.substr(strFile.length + 1, rest.length);

				}else {
					strFile = rest;
					strRest = '';
				}

				//add the lang you just switched to

				strURL = baseurl + strFile + '/nl' + strRest;


			}
			if (strURL.indexOf('.nl')>0 && select.value=='english') {
				//it's .nl and changing lang to english, then add lang var
				baseurl = 'http://www.liquic.nl/';

				rest = strURL.substring(baseurl.length, strURL.length);
				if (rest.indexOf('/')>0) {
					strFile = rest.substr(0, rest.indexOf('/'));
					strRest = '/' + rest.substr(strFile.length + 1, rest.length);
				}else {
					strFile = rest;
					strRest = '';
				}
				//add the lang you just switched to
				strURL = baseurl + strFile + 'en' + strRest;

			}
			//why do we have these lines? Dunno, need to remove two slashes and then add it again for the http://
			strURL = strURL.replace(/\/\//gi, '/');
			strURL = strURL.replace(/http:\//, 'http://');
			window.location = strURL;
		}
	} else {
		location.replace( document.URL );}
}

function setFocus( id ) {
	document.getElementById(id).focus();
}

function adjustPage( amount ) {
	currentpagefield = document.getElementById('page');
	nextpagefield = document.getElementById('next_page');
	nextpagefield.value = String(Number(currentpagefield.value) + amount);
}

function toggleCheckbox( id ) {
	var objCheckbox = document.getElementById( id );
	if( objCheckbox ) objCheckbox.checked = !objCheckbox.checked;
}

function toggleDiv( id, visible ) {
	var objDiv = document.getElementById( id );
	objDiv.className = visible ? 'editinline' : 'editinline-hidden';
}

function toggleVisible( id ) {
	var objDiv = document.getElementById( id );
	objDiv.className = ((objDiv.className == 'hidden') ? 'visible' : 'hidden');
}

function showActionFull( obj, text ) {
	obj.getElementsByTagName('span')[0].innerHTML = text;
}

function showActionImage( obj, imgurl ) {
	var html = '';
	html = '<img src="'+imgurl+'">';
	obj.getElementsByTagName('span')[0].innerHTML = html;
}

function callDynamicScript( id, url ) {
	// construct the proper url

	var fullUrl = url + (url.indexOf("?") < 0 ? "?" : "&") + "noCacheIE=" + (new Date()).getTime();
	var elemHead = document.getElementsByTagName("head").item(0);
	var elemOldScript = document.getElementById( id );

	// check if there is a previous script object and delete it if present
	if( elemOldScript ) {
		elemOldScript.parentNode.removeChild( elemOldScript );
	}

	// Create the script tag
	elemScript = document.createElement("script");

	// Add script object attributes and assign it to the header
	elemScript.setAttribute("type", "text/javascript");
	elemScript.setAttribute("charset", "utf-8");
	elemScript.setAttribute("src", fullUrl);
	elemScript.setAttribute("id", id);
	elemHead.appendChild( elemScript );

}

function getCountrySelected() {
	var objCountry = document.getElementById('country');
	if( objCountry ) {
		return objCountry.value;
	} else {	
		return '';	
	}
}

function replaceSubstring(inputString, fromString, toString) {
	// Goes through the inputString and replaces every occurrence of fromString with toString
	var temp = inputString;
	if (fromString == "") {
		return inputString;
	}
	if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
		while (temp.indexOf(fromString) != -1) {
			var toTheLeft = temp.substring(0, temp.indexOf(fromString));
			var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
			temp = toTheLeft + toString + toTheRight;
		}
	} else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
		var midStrings = new Array("~", "`", "_", "^", "#");
		var midStringLen = 1;
		var midString = "";
		// Find a string that doesn't exist in the inputString to be used
		// as an "inbetween" string
		while (midString == "") {
			for (var i=0; i < midStrings.length; i++) {
				var tempMidString = "";
				for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
				if (fromString.indexOf(tempMidString) == -1) {
					midString = tempMidString;
					i = midStrings.length + 1;
				}
			}
		} // Keep on going until we build an "inbetween" string that doesn't exist
		// Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
		while (temp.indexOf(fromString) != -1) {
			var toTheLeft = temp.substring(0, temp.indexOf(fromString));
			var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
			temp = toTheLeft + midString + toTheRight;
		}
		// Next, replace the "inbetween" string with the "toString"
		while (temp.indexOf(midString) != -1) {
			var toTheLeft = temp.substring(0, temp.indexOf(midString));
			var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
			temp = toTheLeft + toString + toTheRight;
		}
	} // Ends the check to see if the string being replaced is part of the replacement string or not
	return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

/*function calculate_time_zone(curr_time_zone){
	if (curr_time_zone=='' || curr_time_zone==undefined) {
		var rightNow=new Date();
		var jan1=new Date(rightNow.getFullYear(),0,1,0,0,0,0);
		var june1=new Date(rightNow.getFullYear(),6,1,0,0,0,0);
		var temp=jan1.toGMTString();
		var jan2=new Date(temp.substring(0,temp.lastIndexOf(" ")-1));
		temp=june1.toGMTString();
		var june2=new Date(temp.substring(0,temp.lastIndexOf(" ")-1));
		var std_time_offset=(jan1-jan2)/(1000*60*60);
		var daylight_time_offset=(june1-june2)/(1000*60*60);
		var dst;

		if(std_time_offset==daylight_time_offset){
			dst="0";
		}else{
			var hemisphere=std_time_offset-daylight_time_offset;
			if(hemisphere>=0)		std_time_offset=daylight_time_offset;dst="1";
		}
		time_zone_var = convert(std_time_offset)+","+dst;
	}

	else {time_zone_var = curr_time_zone;}

	var i;
	if(document.getElementById('timezone')){
		for(i=0;i<document.getElementById('timezone').options.length;i++){
			if(document.getElementById('timezone').options[i].value==time_zone_var){
				document.getElementById('timezone').selectedIndex=i;
				break;
			}
		}
	}
}
//ends calculate time zone function
*/
function convert(value){

	var hours=parseInt(value);
	value-=parseInt(value);value*=60;
	var mins=parseInt(value);
	value-=parseInt(value);
	value*=60;
	var secs=parseInt(value);
	var display_hours=hours;
	if(hours==0){
		display_hours="00";
	}else if(hours>0){
		display_hours=(hours<10)?"+0"+hours:"+"+hours;
	}else{
		display_hours=(hours>-10)?"-0"+Math.abs(hours):hours;
	}
	mins=(mins<10)?"0"+mins:mins;
	return display_hours+":"+mins;
}


// AJAX	(for autosave function)
function AJAX(){
	try {

		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch(e) {
		try {

			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(ex) {
			try {
				ajax = new XMLHttpRequest();
			}
			catch(exc) {
				alert("Your browser cannot run Ajax");
				ajax = null;
			}
		}
	}
}

//for autosuggest
/* ---------------------------- */
/* XMLHTTPRequest Enable 		*/
/* ---------------------------- */
function createObject() {
	var request_type;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		request_type = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		request_type = new XMLHttpRequest();
	}
	return request_type;
}

var http = createObject();

/* -------------------------- */
/* SEARCH					 */
/* -------------------------- */
function autosuggest() {
	//this is for cities
	q = document.getElementById('city').value;
	c = document.getElementById('country').value;
	if (q.length>2 && c!='') {
		document.getElementById('results').style.visibility="visible";
		// Set te random number to add to URL request
		nocache = Math.random();
		http.open('get', 'libs/get_cities_json.php?q='+q+'&c='+c+'&nocache = '+nocache);
		http.onreadystatechange = autosuggestReply;
		http.send(null);
	}
}
function autosuggest_searchterms() {
	//this is for cats and smads
	
	q = document.getElementById('category').value;

	if (q.length>2 ) {
		document.getElementById('results').style.visibility="visible";
		// Set te random number to add to URL request
		nocache = Math.random();
		http.open('get', 'libs/get_search_terms_json.php?q='+q+'&nocache = '+nocache);
		http.onreadystatechange = autosuggestReply;
		http.send(null);
	}
}
function autosuggestReply() {

	if(http.readyState == 4){
		var response = http.responseText;
		e = document.getElementById('results');
		if(response!=""){
			e.innerHTML=response;
			e.style.display="block";
		} else {
			e.style.display="none";
		}
	}
}
function fillCity(i) {
	document.filter.city.value=i;
	document.getElementById('results').innerHTML = '';
	document.getElementById('results').style.visibility="hidden";
}

function setTarget(){	
	//for the listing_view.tpl to show the long description on the bottom
	var data = document.getElementById('hidedesc');
    document.getElementById('target').innerHTML = data.innerHTML;
    
  }
  
  /* this is just a simple captcha reload */
function reloadCaptcha()
{
	document.getElementById('captcha').src = document.getElementById('captcha').src+ '?' +new Date();
}

var currtab = "tab1";

function showtab( tabname ) {
	
	if(document.getElementById && (!document.layers) && document.body.style) //Kalyan for Mozilla
        {
               // disable header for old tab
               handle = document.getElementById(currtab + "header");
               handle.className = "";
               
               // enable header for new tab
               handle = document.getElementById(tabname + "header");
               handle.className = "current"; 
               
               // hide old tab information
               handle = document.getElementById(currtab);
               handle.style.visibility = 'hidden';
               handle.style.display = 'none';
               
               // show new tab information
               handle = document.getElementById(tabname);
               handle.style.visibility = 'visible';
	       handle.style.display = 'block';

	       currtab = tabname;
	       	       
	       return;      	 
	 }
}

function switchICLang( select ) {
	
	var strURL = document.URL;
	var lang = select.value;
	location=strURL + '&lang='+lang;
}

function clearSearchField(form, field){
	//only do this if the contents of a hidden field (with the original value) are different from the field in question
	var me = document.forms[form];
	//must be a hidden field with suffix "_orig"
	orig_field = me[field+'_orig'].value;

	if (me[field].value == orig_field) {
		me[field].value = '';	
	}
	
}

function fillSearchField(form, field){
	//this is when the user exits the search field but didn't fill in anything... We need to account for this when searching so that they don't actually search for "where?"
	var me = document.forms[form];
	//must be a hidden field with suffix "_orig"
	orig_field = me[field+'_orig'].value;
	if (me[field].value == '') {
		me[field].value = orig_field;	
	}
}

function clearDefaultFields(form, country){
	
	//clear the default fields (city, postcode, category)
	var me = document.forms[form];
	var remEl = document.getElementById('city_orig');
	clearSearchField(form, 'city');
	if ( remEl.parentNode && remEl.parentNode.removeChild ) {
		remEl.parentNode.removeChild(remEl);
	}

	var remEl = document.getElementById('id_orig');
	if (remEl){
	clearSearchField(form, 'id');
	if ( remEl.parentNode && remEl.parentNode.removeChild ) {
		remEl.parentNode.removeChild(remEl);
		}
	}
 
	if (country=='US' || country=='NL'){
		var remEl = document.getElementById('postcode_orig');
		if (remEl){
			clearSearchField(form, 'postcode');
			if ( remEl.parentNode && remEl.parentNode.removeChild ) {
				remEl.parentNode.removeChild(remEl);
			}
		}
	}
}

/* ***** Begin ***************************************************** */
/* got the code from here: http://www.greywyvern.com/code/javascript/fade   */
function fadeObject(id, c1, c2, s1, s2) {
  var self = this;
  this.id      = id;
  this.elem    = false;
  this.colour  = {
    stt: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)],
    end: [parseInt(c2.substr(0, 2), 16), parseInt(c2.substr(2, 2), 16), parseInt(c2.substr(4, 2), 16)],
    now: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)]
  };
  this.steps   = [s1, s2];
  this.dir     = false;
  this.active  = false;
  this.queue   = [];
  this.msg     = [];
  this.message = 0;
  function d2h(num) {
    num = Math.round(num);
    return ((num < 16) ? "0" : "") + num.toString(16);
  }
  this.fade = function(message, direction) {
    this.elem = this.elem || document.getElementById(this.id);
    this.queue.push([message, direction]);
    for (var x = 0; x < this.queue.length; x++) {
      for (var y = x + 1; y < this.queue.length; y++) {
        if (this.queue[x][0] == this.queue[y][0] && this.queue[x][1] != this.queue[y][1]) {
          this.queue.splice(x, 1);
          this.queue.splice(y - 1, 1);
        }
      }
    }
    if (!this.active) setTimeout(function() { self.fadeLoop(); }, 10);
  };
  this.fadeLoop = function() {
    if (!this.active && this.queue.length) {
      if (this.dir && this.message != this.queue[0][0]) this.queue.unshift([this.message, false]);
      var msg = this.queue.shift();
      if (this.msg[msg[0]]) {
        this.active = true;
        this.elem.innerHTML = this.msg[this.message = msg[0]];
        this.dir = msg[1];
      }
    }
    if (this.dir) {
      var c1 = this.colour.stt, c2 = this.colour.end, s = this.steps[0];
    } else var c1 = this.colour.end, c2 = this.colour.stt, s = this.steps[1];
    for (var x = 0, cnow = "", inc = 0; x < 3; x++) {
      this.colour.now[x] += inc = (c2[x] - c1[x]) / s;
      cnow += this.colour.now[x] = (inc < 0) ? Math.max(this.colour.now[x], c2[x]) : Math.min(this.colour.now[x], c2[x]);
    } this.elem.style.color = "#" + d2h(this.colour.now[0]) + d2h(this.colour.now[1]) + d2h(this.colour.now[2]);
    if (cnow == c2.join("")) {
      this.active = false;
      if (!this.queue.length) {
        if (!this.dir) {
          if (this.msg[0]) {
            this.queue.push([0, true]);
            setTimeout(function() { self.fadeLoop(); }, 10);
          } else this.elem.innerHTML = "&nbsp;";
        }
      } else setTimeout(function() { self.fadeLoop(); }, 10);
    } else setTimeout(function() { self.fadeLoop(); }, 10);
  };
  if (window.addEventListener) {
    window.addEventListener('load', function() { self.fade(0, true); }, false); 
  } else if (window.attachEvent)
    window.attachEvent('onload', function() { self.fade(0, true); });
}
/* ***** End ******************************************************* */