/*==========================================================================*\
|| ######################################################################## ||
|| # ILance Marketplace Software
|| # -------------------------------------------------------------------- # ||
|| # Copyright ©2000–2009 ILance Inc. All Rights Reserved.	          # ||
|| # This file may not be redistributed in whole or significant part. 	  # ||
|| # ----------------- ILANCE IS NOT FREE SOFTWARE ---------------------- # ||
|| # http://www.ilance.com | http://www.ilance.com/eula	| info@ilance.com # ||
|| # -------------------------------------------------------------------- # ||
|| ######################################################################## ||
\*==========================================================================*/

/**
* Core Javascript functions for ILance.
*
* @package      iLance
* @version	$Revision: 1.0.0 $
* @author       ILance
*/

/**
* Browser Compatibility
*/
var DOMTYPE = '';
if (document.getElementById)
{
	DOMTYPE = 'std';
}
else if (document.layers)
{
	DOMTYPE = 'ns4';
}
else if (document.all)
{
	DOMTYPE = 'ie4';
}

if (typeof ILSESSION == 'undefined')
{
	ILSESSION = '';
}

/**
* Fetch Browser Agent
*/
var AGENT = navigator.userAgent.toLowerCase();
var checkopera = (AGENT.indexOf('opera') != -1);
var checksaf = ((AGENT.indexOf('safari') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var checkwebtv = (AGENT.indexOf('webtv') != -1);
var checkie = ((AGENT.indexOf('msie') != -1) && (!checkopera) && (!checksaf) && (!checkwebtv));
var checkie4 = ((checkie) && (AGENT.indexOf('msie 4.') != -1));
var checkie7 = ((checkie) && (AGENT.indexOf('msie 7.') != -1));
var checkmoz = ((navigator.product == 'Gecko') && (!checksaf));
var checkkon = (AGENT.indexOf('konqueror') != -1);
var checkns = ((AGENT.indexOf('compatible') == -1) && (AGENT.indexOf('mozilla') != -1) && (!checkopera) && (!checkwebtv) && (!checksaf));
var checkns4 = ((checkns) && (parseInt(navigator.appVersion) == 4));
var checkmac = (AGENT.indexOf('mac') != -1);
var checkchrome = (AGENT.indexOf('chrome') != -1);

/**
* Define popup, delays and other objects
*/
var rotate_delay = 5000;
var current = 0;
var attw = null;
var drww = null;
var checkobj = null;
var ilobjects = new Array();

/**
* AJAX and Regular Expressions Compatibility
*/
var REGEXP_Compatible = (window.RegExp) ? true : false;
var AJAX_Compatible = false;

/**
* Core Functions
*/
function fetch_session_id()
{
	return (ILSESSION == '' ? '' : ILSESSION.substr(2, 32));
}

function fetch_js_object(idname)
{
	if (document.getElementById)
	{
		return document.getElementById(idname);
	}
	else if (document.all)
	{
		return document.all[idname];
	}
	else if (document.layers)
	{
		return document.layers[idname];
	}
	else
	{
		return null;
	}
}

function fetch_js_cookie(name) 
{
	v3cookiename = name + '=';
	v3cookiesize = document.cookie.length;
	v3cookiestart = 0;
	while (v3cookiestart < v3cookiesize) 
	{
		v3cookievalue = v3cookiestart + v3cookiename.length;
		if (document.cookie.substring(v3cookiestart, v3cookievalue) == v3cookiename) 
		{
			var v3cookievalue2 = document.cookie.indexOf (';', v3cookievalue);
			if (v3cookievalue2 == -1) 
			{
				v3cookievalue2 = v3cookiesize;
			}
			return unescape(document.cookie.substring(v3cookievalue, v3cookievalue2));
		}
		v3cookiestart = document.cookie.indexOf(' ', v3cookiestart) + 1;
		if (v3cookiestart == 0) 
		{
			break;
		}
	}
	return null;
}

function update_js_cookie(name, value, expires) 
{
	if (!expires) 
	{
		expires = new Date();
	}
	document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() +  "; path=/";
}

function update_js_collapse_cookie(objid, setcookiedata, cookiename) 
{
	var cookiedata = fetch_js_cookie(cookiename);
	var cookietemp = new Array();
	if (cookiedata != null) 
	{
		cookiedata = cookiedata.split('|');
		for (i in cookiedata) 
		{
			if (cookiedata[i] != objid && cookiedata[i] != '') 
			{
				cookietemp[cookietemp.length] = cookiedata[i];
			}
		}
	}
	if (setcookiedata) 
	{
		cookietemp[cookietemp.length] = objid;
	}
	cookieexpire = new Date();
	cookieexpire.setTime(cookieexpire.getTime() + (500 * 86400 * 365));
	update_js_cookie(cookiename, cookietemp.join("|"), cookieexpire);
}

function toggle(objid) 
{
	if (!REGEXP_Compatible)
	{
		return false;
	}
	
	var cookiename = ILNAME + "collapse";
	obj = fetch_js_object('collapseobj_' + objid);
	img = fetch_js_object('collapseimg_' + objid);
	
	if (obj.style.display == 'none') 
	{
		obj.style.display = '';
		update_js_collapse_cookie(objid, false, cookiename);
		if (img) 
		{
			img_re = new RegExp("_collapsed\\.gif$");
			img.src = img.src.replace(img_re, '.gif');
		}
	}
	else 
	{
		obj.style.display = 'none';
		update_js_collapse_cookie(objid, true, cookiename);
		if (img) 
		{
			img_re = new RegExp("\\.gif$");
			img.src = img.src.replace(img_re, '_collapsed.gif');
		}
	}
	return false;
}

function agreesubmit(el) 
{
	checkobj = el
	if (document.all || document.getElementById) 
	{
		for (i=0; i<checkobj.form.length; i++)
		{
			var tempobj=checkobj.form.elements[i]
			if (tempobj.type.toLowerCase() == 'submit')
				tempobj.disabled=!checkobj.checked
		}
	}
}

function defaultagree(el) 
{
	if (!document.all && !document.getElementById) 
	{
		if (window.checkobj && checkobj.checked)
		{
			return true
		}
		else 
		{
			alert(phrase['_please_read_accept_terms_to_submit_form'])
			return false
		}
	}
}

function confirm_js(message)
{
	grayscale = document.getElementsByTagName("html");
	grayscale[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
	if (confirm(message))
	{
		return true;
	}
	else
	{
		grayscale[0].style.filter = "";
		return false;
	}
}

function alert_js(message)
{
	grayscale = document.getElementsByTagName("html");
	grayscale[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
	if (alert(message))
	{
		return true;
	}
	else
	{
		grayscale[0].style.filter = "";
		return false;
	}	
}

function log_out() 
{
	grayscale = document.getElementsByTagName("html");
	grayscale[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
	if (confirm(phrase['_are_you_ready_to_log_out']))
	{
		return true;
	}
	else
	{
		grayscale[0].style.filter = "";
		return false;
	}
}

function showImage(imagename, imageurl, errors)
{
	document[imagename].src = imageurl;
	if (!haveerrors && errors)
	{
		haveerrors = errors;
		if (obj = fetch_js_object('inlineerror'))
		{
			obj.innerHTML = '<img name="inlineerror" src="images/default/icons/fieldempty.gif" width="21" height="13" border="0" alt="Please fix any errors above" />';
		}
	}
}

function noenter()
{
	return !(window.event && window.event.keyCode == 13); 
}

function createWindow(u, n, w, h, r)
{
	args = 'width='+w+',height='+h+',resizable=no,scrollbars=yes,status=0';
	remote = window.open(u,n,args);
	if (remote != null) 
	{
		if (remote.opener == null)
		{
			remote.opener =  self ;
		}
	}
	if (r == 1)
	{
		return remote;
	}
}

function Attach(url) 
{
	if (!attw || attw.closed)
	{
		attw = createWindow(url, 'attachwin', 520, 400, 1);
	}
	attw.focus();
}

function toggle_tr(target)
{
	obj = fetch_js_object(target);
	obj.style.display = (obj.style.display == 'none') ? 'inline' : 'none';
}

function toggle_more(target, showmoreid, moretext, lesstext, showmoreicon)
{
	cookiename = ILNAME + "deflate";
	
	obj = (document.all) ? document.all[target] : document.getElementById(target);
	//obj.style.display = (obj.style.display == 'none') ? 'inline' : 'none';
	
	if (obj.style.display == 'none') 
	{
		obj.style.display = 'inline';
		update_js_collapse_cookie(target, true, cookiename);
	}
	else 
	{
		obj.style.display = 'none';
		update_js_collapse_cookie(target, false, cookiename);
	}
	
	obj2 = (document.all) ? document.all[showmoreid] : document.getElementById(showmoreid);
	obj2.style.fontweight = 'bold';
	obj2.innerText = (obj.style.display == 'none') ? moretext : lesstext;
	
	obj3 = (document.all) ? document.all[showmoreicon] : document.getElementById(showmoreicon);
	obj3.src = (obj.style.display == 'none') ? IMAGEBASE + 'icons/arrowdown2.gif' : IMAGEBASE + 'icons/arrowup2.gif';
	
	return false;
}

function toggle_paid(target) 
{
	obj = fetch_js_object(target);
	if (obj.style.display == 'none') 
	{
		obj.style.display = 'inline';
	}
}

function toggle_free(target) 
{
	obj = fetch_js_object(target);
	if (obj.style.display == 'inline') 
	{
		obj.style.display = 'none';
	}
}

function toggle_hide(target)
{
	obj = fetch_js_object(target);
	obj.style.display = (obj.style.display == 'none') ? 'none' : 'none';
}

function toggle_show(target)
{
	obj = fetch_js_object(target);
	obj.style.display = (obj.style.display == 'none') ? '' : '';
}

function trim(field)
{
	value = field;
	while (value.charAt(value.length - 1) == " ") 
	{
		value = value.substring(0, value.length-1);
	} 
	while (value.substring(0, 1) == " ") 
	{
		value = value.substring(1, value.length);
	}
	
	return value;
}

function popUP(mypage, myname, w, h, scroll, titlebar) 
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) 
	{
		win.window.focus();
	}
}

function urlswitch(styleobj, _type)
{
	var themeid = styleobj.options[styleobj.selectedIndex].value;
	if (themeid == '')
	{
		return;
	}
	var url = new String(window.location);
	var fragment = new String('');
	url = url.split('#');
	if (url[1])
	{
		fragment = '#' + url[1];
	}
	url = url[0];
	if (_type == 'dostyle')
	{
		if (url.indexOf('styleid=') != -1)
		{
			re = new RegExp("styleid=\\d+&?");
			url = url.replace(re, '');
		}
	}
	else
	{
	    if (url.indexOf('language=') != -1)
	    {
		    re = new RegExp("language=\\d+&?");
		    url = url.replace(re, '');
	    }
	}
	if (url.indexOf('?') == -1)
	{
		url += '?';
	}
	else
	{
		endchar = url.substr(url.length - 1);
		if (endchar != '&' && endchar != '?')
		{
			url += '&';
		}
	}
	if (_type == 'dostyle')
	{
		window.location = url + 'styleid=' + themeid + fragment;
	}
	else
	{
		window.location = url + 'language=' + themeid + fragment;
	}
}

function textcount(field, countfield, maxlimit) 
{
	if (field.value.length > maxlimit)
	{
		field.value = field.value.substring(0, maxlimit);
	}
	else
	{
		countfield.value = maxlimit - field.value.length;
	}
}

function populate_countries_pulldown(cboCountry, cboState, sDefaultCountry)
{
	var sDefault, sCountry;
	var selectOption = -1;
	
	cboCountry.options.length = 0;
	
	for (i = 0; i < sCountryString.split("|").length; i++)
	{
		sCountry = sCountryString.split("|")[i];
		if (sDefaultCountry == sCountry)
		{
			sDefault = true;
			if (navigator.appName == "Microsoft Internet Explorer")
			{
				//cboState.focus();
			}
		}
		else
		{
			sDefault = false;
		}
		if (sDefault)
		{
			var oo = new Option(sCountry, sCountry, sDefault, sDefault);
			oo.setAttribute("selected", "true");
			cboCountry.options[i] = oo;
			selectOption = i;
		}
		else
		{
			cboCountry.options[i] = new Option(sCountryString.split("|")[i]);
		}
	}
	if (selectOption > -1)
	{
		cboCountry.selectedIndex = selectOption;
	}
}

function populate_states_pulldown(cboCountry, cboState, sDefaultState)
{
	var sState, sDefault;
	var selectOption = -1;
	
	cboState.options.length = 0;
	
	for (i = 0; i < sStateArray[cboCountry.selectedIndex].split("|").length; i++)
	{
		sState = sStateArray[cboCountry.selectedIndex].split("|")[i];
		if (sDefaultState == sState)
		{
			sDefault = true;
			selectOption = i;
			if (navigator.appName == "Microsoft Internet Explorer")
			{
				//cboState.focus();
			}
		}
		else
		{
			sDefault = false;
		}
		if (sDefault)
		{
			var oo = new Option(sState, sState, sDefault, sDefault);
			oo.setAttribute("selected", "true");
			cboState.options[i] = oo;	
		}
		else
		{
			cboState.options[i] = new Option(sState,sState);
		}
	}
	if (selectOption > -1)
	{
		cboState.selectedIndex = selectOption;
	}
}

function populate_cities_pulldown(cboState, cboCity, sDefaultCity)
{
	var sState, sCity, sDefault;
	var selectOption = -1;
	
	cboCity.options.length = 0;
	
	for (i = 0; i < sCityArray[cboState[cboState.selectedIndex].text].split("|").length; i++)
	{
		sCity = sCityArray[cboState[cboState.selectedIndex].text].split("|")[i];
		if (sDefaultCity == sCity)
		{
			sDefault = true;
			selectOption = i;
			if (navigator.appName == "Microsoft Internet Explorer")
			{
				//cboCity.focus();
			}
		}
		else
		{
			sDefault = false;
		}
		if (sDefault)
		{
			var oo = new Option(sCity, sCity, sDefault, sDefault);
			oo.setAttribute("selected", "true");
			cboCity.options[i] = oo;	
		}
		else
		{
			cboCity.options[i] = new Option(sCity, sCity);
		}
	}
	if (selectOption > -1)
	{
		cboCity.selectedIndex = selectOption;
	}
}

function fetch_tags(parentobj, tag)
{
	if (parentobj == null)
	{
		return new Array();
	}
	else if (typeof parentobj.getElementsByTagName != 'undefined')
	{
		return parentobj.getElementsByTagName(tag);
	}
	else if (parentobj.all && parentobj.all.tags)
	{
		return parentobj.all.tags(tag);
	}
	else
	{
		return new Array();
	}
}

function construct_phrase()
{
	if (!arguments || arguments.length < 1 || !REGEXP_Compatible)
	{
		return false;
	}
	var args = arguments;
	var str = args[0];
	var re;
	for (var i = 1; i < args.length; i++)
	{
		re = new RegExp("%" + i + "\\$s", 'gi');
		str = str.replace(re, args[i]);
	}
	return str;
}

function construct_textarea_height(boxid, pixelvalue)
{
	var box = fetch_js_object(boxid);
	var boxheight = parseInt(box.style.height);
	var newheight = boxheight + pixelvalue;
	if (newheight > 0)
	{
		box.style.height = newheight + "px";
	}
	return false;
}

function mediashare_validate(field, errtext)
{
	if (field.value == '')
	{
		alert('You cannot continue without a ' + errtext);
		return false;
	}
	return true;
}

function unescape_cdata(str)
{
	var r1 = /<\=\!\=\[\=C\=D\=A\=T\=A\=\[/g;
	var r2 = /\]\=\]\=>/g;
	return str.replace(r1, '<![CDATA[').replace(r2, ']]>');
}

function urlencode(text)
{
	text = escape(text.toString()).replace(/\+/g, "%2B");
	var matches = text.match(/(%([0-9A-F]{2}))/gi);
	if (matches)
	{
		for (var matchid = 0; matchid < matches.length; matchid++)
		{
			var code = matches[matchid].substring(1,3);
			if (parseInt(code, 16) >= 128)
			{
				text = text.replace(matches[matchid], '%u00' + code);
			}
		}
	}
	text = text.replace('%25', '%u0025');
	return text;
}

function toggle_tab(tabid, obj, obj2, taboutputdiv)
{
	var linkList;
	var newtab;
	
	linkList = fetch_js_object(tabid).getElementsByTagName('li');
	for (i = 0; i < linkList.length; i++)
	{
		linkList[i].className = '';
	}
	
	fetch_js_object(obj).className = 'on';	
	newtab = fetch_js_object(obj2).innerHTML;
	fetch_js_object(taboutputdiv).innerHTML = newtab;
}

function toggle_big_tab(obj, phrase)
{
	var linkList;
	linkList = fetch_js_object('skilltabs').getElementsByTagName('li');
	for (i = 0; i < linkList.length; i++)
	{
		linkList[i].className = '';
	}
	
	fetch_js_object(obj).className = 'on';
	fetch_js_object('tabtext').innerHTML = phrase;
}

function fetch_watchlist_response()
{
	if (xmldata.handler.readyState == 4 && xmldata.handler.status == 200 && xmldata.handler.responseXML)
	{
		// format response
		response = fetch_tags(xmldata.handler.responseXML, 'status')[0];
		phpstatus = xmldata.fetch_data(response);
		
		if (phpstatus == 'addeditem')
		{
			fetch_js_object('itemwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_you_are_watching_this_item'] + '</span>&nbsp;&nbsp;&nbsp;<span class="smaller gray">[ <span class="blue"><a href="watchlist.php">View Watchlist</a></span> ]</span>';
		}
		else if (phpstatus == 'alreadyaddeditem')
		{
			fetch_js_object('itemwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_this_item_is_already_added_to_your_watchlist'] + '</span>';	
		}
		else if (phpstatus == 'addedseller')
		{
			fetch_js_object('sellerwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_seller_is_in_favorites'] + '</span>&nbsp;&nbsp;&nbsp;<span class="smaller gray">[ <span class="blue"><a href="watchlist.php?tab=2">View Watchlist</a></span> ]</span>';
		}
		else if (phpstatus == 'alreadyaddedseller')
		{
			fetch_js_object('sellerwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_this_seller_is_already_added_to_your_watchlist'] + '</span>';	
		}
		else if (phpstatus == 'error')
		{
			fetch_js_object('itemwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_please_signin_to_save_items_to_watchlist'] + '</span>';
			fetch_js_object('sellerwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_please_signin_to_save_favorite_sellers'] + '</span>';
		}
		
		xmldata.handler.abort();
	}
}

function add_item_to_watchlist(projectid, userid)
{
	if (userid == '' || userid == 0 || projectid == '' || projectid == 0)
	{
		fetch_js_object('itemwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_please_signin_to_save_items_to_watchlist'] + '</span>';
		return false;
	}
	
	// set ajax handler
	xmldata = new AJAX_Handler(true);
	
	// url encode the vars
	projectid = urlencode(projectid);
	xmldata.projectid = projectid;
	
	userid = urlencode(userid);
	xmldata.userid = userid;
	
	xmldata.onreadystatechange(fetch_watchlist_response);

	// send data to php
	xmldata.send('ajax.php', 'do=addwatchlist&projectid=' + projectid + '&userid=' + userid); 
}

function add_seller_to_watchlist(sellerid, userid)
{
	if (userid == '' || userid == 0 || sellerid == '' || sellerid == 0)
	{
		fetch_js_object('itemwatchlistresponse').innerHTML = '<span class="gray">' + phrase['_please_signin_to_save_favorite_sellers'] + '</span>';
		return false;	
	}
	
	// set ajax handler
	xmldata = new AJAX_Handler(true);
	
	// url encode the vars
	sellerid = urlencode(sellerid);
	xmldata.sellerid = sellerid;
	
	userid = urlencode(userid);
	xmldata.userid = userid;
	
	xmldata.onreadystatechange(fetch_watchlist_response);

	// send data to php
	xmldata.send('ajax.php', 'do=addwatchlist&sellerid=' + sellerid + '&userid=' + userid);
}

/*======================================================================*\
|| ####################################################################
|| # CVS: $RCSfile: functions.js,v $ - $Revision: 1.00 $
|| ####################################################################
\*======================================================================*/