/*
 * WILDFIRE - the internet content and commerce management and application development suite
 * Copyright (C) 2005-2006 Nick Donald & Colin Redpath
 *
 * For further information visit:
 * 		http://www.spreadwildfire.net
 *
 * File Name:
 *
 *
 * File Authors:
 * 		Nick Donald & Colin Redpath (info@spreadwildfire.net)
 */

//drag and drop
var ie=document.all;
var nn6=document.getElementById&&!document.all;

/*
	Ajax Handlers
*/

// Load an XML document
function loadXMLDoc(uri, callback)
{
	var req = null;
	// Native XMLHttpRequest object
    if (window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
        if (req){
			try {
				//req.onreadystatechange = callback;
	          	req.onreadystatechange = function(){if(req.readyState == 4) doCallback(req, callback)};
				req.open('GET', approot+uri, true);
				req.send(null);
			} catch(e) {
				alert("Unable to send request for data.\n\n" + e.toString());
				delete req;
				req = null;
			}
        }else{
			alert("Unable to create new XMLHTTPRequest object.");
		}
    }else if (window.ActiveXObject){
       	req = new ActiveXObject('Microsoft.XMLHTTP');

        if (req)
        {
			try
			{
	          	req.onreadystatechange = function(){if(req.readyState == 4) doCallback(req, callback)};
            	req.open('GET', approot+uri, true);
            	req.send();
			}catch(e){
				alert("Unable to send request for data.\n\n" + e.toString());
				delete req;
				req = null;
			}
        }else{
			alert("Unable to create new Microsoft.XMLHTTP ActiveXObject.");
		}
    }

    if (!req)
    {
		alert('Unable to send request for data. Please try again.')
	}
}

function doCallback(http, callback)
{
	if (callback != null) eval(callback+"(http)");
}

//Send Form Data
function postData(uri, data)
{
	var http = null;
	if(window.XMLHttpRequest)
	{
		http = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		http = new ActiveXObject("Microsoft.XMLHTTP");
	}

	http.onreadystatechange = function(){if(http.readyState == 4)handleSave(http);};
	http.open("POST", approot+uri, true);
	http.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	http.send(data);
}

function sendViaAjax(form, method, str)
{
	var data = "";
	data += addToPost(data,"aj",method);
	data += addToPost(data,"fn",form.name);
	for (var i=0;i<form.elements.length;i++)
	{
		if (form.elements[i].name != null)
		{
			if (form.elements[i].type != "checkbox" || form.elements[i].checked) data += addToPost(data, form.elements[i].name, form.elements[i].value);
		}
	}

	if (str) data += "&"+str;
	if (data != "") postData(form.action, data);
}

function addToPost(postdata, key, value)
{
	if (value != null)
	{
		value = value.toString().replace(/\+/g,"W__I__L__D__F__I__R__E__A__J__A__X__P__L__U__S");
		return (postdata != ""?"&":"")+key+"="+escape(value);
	}else return "";
}

function gebi(id)
{
	return document.getElementById(id);
}

/***********************************************
 * Javascript Ticker
 ***********************************************/
//defaults
var tickers = new Array();
var charTimeOut = 50;
var headlineTimeout = 3000;

// Ticker startup
function initTicker(id, array, title)
{
	if (!document.getElementById) return;
	//write ticker screen object	document.write('<div class="ticker"><a href="#" id="'+id+'"></a></div>');


	//get the ticker screen object
	var ticker 	= document.getElementById(id);


	//get max # chars for ticker based on # M's that can fit
	var maxW	= ticker.parentNode.offsetWidth;
	var i		= 0;
	ticker.style.visibility = "hidden";
	while (ticker.offsetWidth < maxW)
	{
		ticker.innerHTML += "M";
		i++;
	}
	ticker.innerHTML = '<span class="tickerTitle">'+title+'&nbsp;</span>';
	ticker.style.visibility = "visible";

	if (array[0].length == 0) return;
	//IE frig to increase speed & stop prcessor overload in floating layouts
	if (ie)
	{
		ticker.parentNode.parentNode.style.height = ticker.parentNode.parentNode.offsetHeight+"px";
		ticker.parentNode.style.position = "absolute";
	}

	//create ticker object
	var tmp			= new Object();
	tmp.id			= id;
	tmp.Data		= array;
	tmp.Index		= -1;
	tmp.Position	= 0;
	tmp.Count		= tmp.Data[0].length; //# headlines
	tmp.Title		= title; //ticker title text
	tmp.MaxLen		= i-5; //max # chars

	//add to array
	tickers[tickers.length] = tmp;

	//start ticking
	tick(tickers.length-1);
}

function tick(obIndex)
{
	//get ticker object & set vars
	var ob			= tickers[obIndex];
	var id			= ob.id; //screen object
	var count		= ob.Count; //number of headlines in ticker
	var index		= ob.Index; //current headline index
	var position	= ob.Position; //ticker position
	var data		= ob.Data; //array of ticker data
	var title 		= ob.Title; //ticker title text
	var headline	= ob.Headline; //current headline
	var maxLen		= ob.MaxLen; //max available length

	//get ticker screen object
	var ticker = document.getElementById(id);

	//get data arrays from ticker object
	var headlines	= data[0];
	var links		= data[1];
	var targets 	= data[2];

	//init timeout var
	var timeout;

	//if new headline
	if(position == 0)
	{
		//increment headline index
		index++;

		//reset headline index to 0 if @ end
		index = index % count;

		//store index in object
		ob.Index = index;

		//get headline from  headlines array
		headline = headlines[index].replace(/&quot;/g,'"');

		//truncate headline if too long
		if (headline.length > maxLen)
		{
			//create substring
			headline = headline.substr(0,maxLen);

			//move to last instance of ' '
			headline = headline.substr(0, headline.lastIndexOf(" "));

			//append elipses
			headline += " ...";
		}

		//update headline in ticker object
		ob.Headline = headline;

		//add href to ticker screen object
		var link = links[index];
		ticker.href = link;

		//set ticker screen object target
		ticker.target = targets[index] == 1 ? "_blank" : "_self";
	}

	var s = ""; //seperator

	if(position != headline.length) //!eol
	{
		//increment ticker posn & set short pause
		ob.Position++;
		timeout = charTimeOut;

		//set seperator
		s = position % 2 == 1 ? "&nbsp;" : "_";
	}else{
		//init new headline & set long pause
		ob.Position = 0;
		timeout = headlineTimeout;
	}

	//update ticker screen object
	ticker.innerHTML = '<span class="tickerTitle">'+title+'&nbsp;</span>'+headline.substring(0,position)+s;

	//set timeout
	window.setTimeout("tick('"+obIndex+"')", timeout);
}

/***********************************************
* Pausing up-down scroller- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/
function initScroller(id)
{
	var tmp = new Array();
	var headlines = eval("h_"+id);
	var links	  = eval("l_"+id);

	for (var i=0;i<headlines.length;i++)
	{
		tmp[tmp.length] = '<a href="'+links[i]+'">'+headlines[i]+'</a>';
	}

	new pausescroller(tmp, "scroller_"+id, "textscroller", 3000);
}


function pausescroller(content, divId, divClass, delay){
this.content=content //message array content
this.tickerid=divId //ID of ticker div to display information
this.delay=delay //Delay between msg change, in miliseconds.
this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
this.hiddendivpointer=1 //index of message array for hidden div
document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>')
var scrollerinstance=this
if (window.addEventListener) //run onload in DOM2 browsers
window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
else if (window.attachEvent) //run onload in IE5.5+
window.attachEvent("onload", function(){scrollerinstance.initialize()})
else if (document.getElementById) //if legacy DOM browsers, just start scroller after 0.5 sec
setTimeout(function(){scrollerinstance.initialize()}, 500)
}

// -------------------------------------------------------------------
// initialize()- Initialize scroller method.
// -Get div objects, set initial positions, start up down animation
// -------------------------------------------------------------------

pausescroller.prototype.initialize=function(){
this.tickerdiv=document.getElementById(this.tickerid)
this.visiblediv=document.getElementById(this.tickerid+"1")
this.hiddendiv=document.getElementById(this.tickerid+"2")
this.visibledivtop=parseInt(pausescroller.getCSSpadding(this.tickerdiv))
//set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
this.visiblediv.style.width=this.hiddendiv.style.width=this.tickerdiv.offsetWidth-(this.visibledivtop*2)+"px"
this.getinline(this.visiblediv, this.hiddendiv)
this.hiddendiv.style.visibility="visible"
var scrollerinstance=this
document.getElementById(this.tickerid).onmouseover=function(){scrollerinstance.mouseoverBol=1}
document.getElementById(this.tickerid).onmouseout=function(){scrollerinstance.mouseoverBol=0}
if (window.attachEvent) //Clean up loose references in IE
window.attachEvent("onunload", function(){scrollerinstance.tickerdiv.onmouseover=scrollerinstance.tickerdiv.onmouseout=null})
setTimeout(function(){scrollerinstance.animateup()}, this.delay)
}


// -------------------------------------------------------------------
// animateup()- Move the two inner divs of the scroller up and in sync
// -------------------------------------------------------------------

pausescroller.prototype.animateup=function(){
var scrollerinstance=this
if (parseInt(this.hiddendiv.style.top)>(this.visibledivtop+5)){
this.visiblediv.style.top=parseInt(this.visiblediv.style.top)-5+"px"
this.hiddendiv.style.top=parseInt(this.hiddendiv.style.top)-5+"px"
setTimeout(function(){scrollerinstance.animateup()}, 50)
}
else{
this.getinline(this.hiddendiv, this.visiblediv)
this.swapdivs()
setTimeout(function(){scrollerinstance.setmessage()}, this.delay)
}
}

// -------------------------------------------------------------------
// swapdivs()- Swap between which is the visible and which is the hidden div
// -------------------------------------------------------------------

pausescroller.prototype.swapdivs=function(){
var tempcontainer=this.visiblediv
this.visiblediv=this.hiddendiv
this.hiddendiv=tempcontainer
}

pausescroller.prototype.getinline=function(div1, div2){
div1.style.top=this.visibledivtop+"px"
div2.style.top=Math.max(div1.parentNode.offsetHeight, div1.offsetHeight)+"px"
}

// -------------------------------------------------------------------
// setmessage()- Populate the hidden div with the next message before it's visible
// -------------------------------------------------------------------

pausescroller.prototype.setmessage=function(){
var scrollerinstance=this
if (this.mouseoverBol==1) //if mouse is currently over scoller, do nothing (pause it)
setTimeout(function(){scrollerinstance.setmessage()}, 100)
else{
var i=this.hiddendivpointer
var ceiling=this.content.length
this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
this.hiddendiv.innerHTML=this.content[this.hiddendivpointer]
this.animateup()
}
}

pausescroller.getCSSpadding=function(tickerobj){ //get CSS padding value, if any
if (tickerobj.currentStyle)
return tickerobj.currentStyle["paddingTop"]
else if (window.getComputedStyle) //if DOM2
return window.getComputedStyle(tickerobj, "").getPropertyValue("padding-top")
else
return 0
}

//google maps
var gmarkers = [];

function renderGoogleMap(mapid,start_lon, start_lat, mag, largemap, gmap, arr_lon, arr_lat, arr_label, arr_name)
{
	try
	{
		if(GBrowserIsCompatible())
		{
			var map = new GMap(document.getElementById(mapid));
			if(largemap) map.addControl(new GLargeMapControl());
			if(gmap) map.addControl(new GMapTypeControl());
			map.centerAndZoom(new GPoint(start_lon,start_lat), mag);
			var longditudes = arr_lon.split("|");
			var lattitudes = arr_lat.split("|");
			var labels = arr_label.split("|");
			var names = arr_name.split("|");
			if(longditudes.length > 0)
			{
				gmarkers = [];
				for(var i=0;i<longditudes.length;i++)
				{
					addGoogleMapMarker(longditudes[i],lattitudes[i],labels[i],names[i],map);
				}
				GEvent.addListener(map, "click", function(overlay, point) {
					if (overlay) {
					  if (overlay.my_html) {
						overlay.openInfoWindowHtml('<div style="white-space:nowrap;">'+overlay.my_html+'</div>');
					  }
					}
				});
				var s_html = "";
				for (var i=0; i < gmarkers.length; i++)
				{
					if (gmarkers[i].my_name) s_html += '<a href="javascript:myclickGoogle(' + i + ')">' + gmarkers[i].my_name + '</a><br/>';
				}
				document.getElementById("linkbar").innerHTML = s_html;
			}
		}
	}catch(E){
		alert("You do not have a valid license key for GoogleMaps, please register with GoogleMaps and add the key to the site properties module.");
	}
}

function addGoogleMapMarker(lon,lat,label,name,map)
{
	var marker = new GMarker(new GPoint(lon, lat));
	marker.my_html = label;
	marker.my_name = name;
	map.addOverlay(marker);
	gmarkers.push(marker);
}

function myclickGoogle(i)
{
	gmarkers[i].openInfoWindowHtml('<div style="white-space:nowrap;">'+gmarkers[i].my_html+'</div>');
}

/******************************************************************************************************
 *
 *	SNAPFAX CODE STARTS
 *
 ******************************************************************************************************/
// snapfax shuffle
function initShuffle()
{
	if (document.getElementById)
	{
		var oParent = gebi("discounts");
		for (var i=0;i<oParent.childNodes.length;i++)
		{
			if (oParent.childNodes[i].tagName == "DIV" && oParent.childNodes[i].className == "shuffle")
			{
				shuffle(oParent.childNodes[i].id);
			}
		}
		oParent.style.visibility = "visible";
	}
}

function shuffle(id)
{
	var oParent = gebi(id);
	var candidates = new Array();
	for (var i=0;i<oParent.childNodes.length;i++)
	{
		if (oParent.childNodes[i].tagName == "DIV" && oParent.childNodes[i].className != "promo_header")
		{
			oParent.childNodes[i].id = id + "_" + i;
			candidates[candidates.length] = oParent.childNodes[i].id;
		}
	}
	candidates = fisherYates(candidates)
	var clone = oParent.cloneNode(false);
	for (var i=0;i<oParent.childNodes.length;i++)
	{
		if (oParent.childNodes[i].tagName == "DIV" && oParent.childNodes[i].className.indexOf("promo_header") > -1)
			clone.appendChild(oParent.childNodes[i]);
	}
	for (var i = 0;i<candidates.length;i++)
	{
		if (gebi(candidates[i]).className == "shuffle") shuffle(candidates[i]);
		clone.appendChild(gebi(candidates[i]));
	}
	oParent.parentNode.insertBefore(clone, oParent);
	oParent.parentNode.removeChild(oParent);
}

function fisherYates(myArray)
{
	var i = myArray.length;
	if ( i == 0 ) return false;
	while ( --i )
	{
		var j = Math.floor( Math.random() * ( i + 1 ) );
		var tempi = myArray[i];
		var tempj = myArray[j];
		myArray[i] = tempj;
		myArray[j] = tempi;
	}
	return myArray;
}

function checkAllCats()
{
	var oC = document.getElementsByTagName("input");
	for (var i=0;i<oC.length;i++)
	{
		if(oC[i].type == "checkbox") oC[i].checked = true;
	}
}

// client ajax js
var isstudent = true;

function getInstitutions()
{
	var city = document.getElementById("cityAjax").value;
	// clear other city and institute values
	gebi("sys_usr_user.institute_city__other").value = "";

	if(gebi("sys_usr_user.institution__other") == null) isstudent = false;

	if(isstudent) gebi("sys_usr_user.institute_city__other").value = "";

	var selectedText = document.getElementById("cityAjax").options[document.getElementById("cityAjax").selectedIndex].text;
	if(selectedText != "Other not listed" && city.length > 0)
	{
		document.getElementById("cityAjax_otherdiv").style.display = "none";
		if(isstudent)
		{
			document.getElementById("instAjax_otherdiv").style.display = "none";
			document.getElementById("instAjax").readonly= false;
			var sql = "Select institute FROM usr_snapfax_institute WHERE city='"+city+"'";
			var uri = "/_/ajax/?sql="+sql+"&root=insitutes&node=inst";
			loadXMLDoc(uri, "handleLoadInstitutes");
		}
	}else if(selectedText == "Other not listed") {
		document.getElementById("cityAjax_otherdiv").style.display = "block";
		if(isstudent)
		{
			document.getElementById("instAjax_otherdiv").style.display = "block";
			document.getElementById("instAjax").readonly = true;
			document.getElementById("instAjax").value = "";
			var oSel = document.getElementById("instAjax");
			while(oSel.childNodes.length > 2)
			{
				oSel.removeChild(oSel.childNodes[2]);
			}
		}
	}
}
function getInstitutionsOther()
{
	var od = document.getElementById("instAjax_otherdiv");
	var selectedText = document.getElementById("instAjax").options[document.getElementById("instAjax").selectedIndex].text;
	if(selectedText == "Other not listed")
	{
		od.style.display = "block";
	}else{
		od.style.display = "none";
	}
}

function checkFieldOther()
{
	gebi("sys_usr_user.course__other").value = "";
	var od = document.getElementById("studyAjax_otherdiv");
	var selectedText = document.getElementById("studyAjax").options[document.getElementById("studyAjax").selectedIndex].text;
	if(selectedText == "Other not listed")
	{
		od.style.display = "block";
	}else{
		od.style.display = "none";
	}
}

function checkIfInvalid()
{
	if(document.getElementById("cityAjax").value.length > 0 && document.getElementById("instAjax").value.length == 0) getInstitutions();
	if(gebi("sys_usr_user.institute_city__other").value.length > 0)
	{
		var oSel = document.getElementById("instAjax");

		while(oSel.childNodes.length > 2)
		{
			oSel.removeChild(oSel.childNodes[2]);
		}

		gebi("instAjax_otherdiv").style.display = "block";

	}
}

function handleLoadInstitutes(http)
{
	try
	{
		var xmlDocument = http.responseXML;
		var insitutes = xmlDocument.getElementsByTagName("insitutes").item(0);
		var oSel = document.getElementById("instAjax");
		if(insitutes.childNodes.length > 0)
		{
			// remove
			while(oSel.childNodes.length > 2)
			{
				oSel.removeChild(oSel.childNodes[2]);
			}
		}

		for (var i=0;i<insitutes.childNodes.length;i++)
		{
			var oOpt = document.createElement("OPTION");
			oOpt.innerHTML = insitutes.childNodes[i].getAttribute("institute");
			oOpt.value = insitutes.childNodes[i].getAttribute("institute");
			oSel.appendChild(oOpt);
		}

		// add other
		var oOpt = document.createElement("OPTION");
		oOpt.innerHTML = "Other not listed";
		oOpt.value = "";
		oSel.appendChild(oOpt);


	}catch(E){
		alert(E);
	}
}

// needs to chop length of ta and alert user
function checkTALength(oE,len)
{
}

/******************************************************************************************************
 *
 *	SNAPFAX CODE ENDS
 *
 ******************************************************************************************************/

function clearSearchMask(oE)
{
	if(oE.value == "Search for") oE.value = "";
}