// JavaScript Document

function login(secure){
	//loginCookie = writeCookie('login', sessionid, '1', 'https://media6.magma.ca/', true);
	document.location.href = secure +  "secure/register.php"; 
	return false;
}

function logout(){
	document.location.href =  WEBROOT + "/logout.php";
	return false;
}

// Example:

// writeCookie("myCookie", "my name", 24);

// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.

function writeCookie(name, value, hours, domain, secure){

  var expire = "";

  if(hours != null)

  {

    expire = new Date((new Date()).getTime() + hours * 3600000);

    expire = "; expires=" + expire.toGMTString();

  }
  if(secure){
	strSecure = "secure=true;"  
  }else{
	strSecure = "";
  }

  document.cookie = name + "=" + escape(value) + expire + "; path=/; domain=" + domain + "; " + strSecure;

}


function register_validate(){
	return false;
}

function login_validate(){
	return false;
}

function ai(secure, regkey){
	document.location.href = secure +  "secure/assume.process.php?rk=" + regkey; 
}

var myTimer;
var r, b, g;

function showErr(){
	var err = document.getElementById("errMsg");
	err.style.height = '20px';
	err.style.borderBottom = "2px solid #990000";
	//TODO: loop through background colours?
	setBanner();
}

function setBanner(){
	//cycle the background colour of the errMsg div
	//go to #ffff99 from #ffcc00
	r = 255;
	g = 204; //parseInt(CC, 16);
	b = 0;
	myTimer = setInterval("incrementColour()", 25);
}

function incrementColour(){
	if((g < 250) || (b < 205) ){
		if(g < 250){
			g = g + 1;
		}
		if(b < 205){
			b = b + 2;
		}
		if(banner = document.getElementById("errMsg")){
			rh = r.toString(16);
			gh = g.toString(16);
			bh = b.toString(16);
			rh.length==1?rh="0"+rh:rh=rh;
			gh.length==1?gh="0"+gh:gh=gh;
			bh.length==1?bh="0"+bh:bh=bh;
			color = "#" + rh + gh + bh;
			banner.style.backgroundColor = color;
		}
	}else{
		clearInterval(myTimer);	
	}
}

function sendEmail(span){
	//this takes the email address from the span and opens the mail client window after flipping the text
	address = span.innerHTML;
	newAddress = "";
	//now flip the address
	//not if this is Safari
	if((navigator.userAgent.toLowerCase().indexOf("safari") == -1) || 
		((navigator.userAgent.toLowerCase().indexOf("opera") != -1)&& parseFloat(navigator.appVersion) < 8.0 )){
		for(i=address.length-1; i>=0; i--){
			newAddress += address.substr(i, 1);	
		}
	}else{
		newAddress = address;	
	}
	newAddress = "mailto:" + newAddress;
	//window.open(newAddress, '', '');
	location.href = newAddress;
}

function toggleP(obj){
	if(obj.style.display == 'block'){
		obj.style.display = 'none';	
	}else{
		obj.style.display = 'block';
	}
}

function toggleRename(obj, get, set){
	strName = obj.id.replace(get, set);
	toggleP(document.getElementById(strName));
}

function toggleOpen(num){
	if(num != "0"){
		strName = "regList" + num.toString();
		//alert(strName);
		toggleP(document.getElementById(strName));
	}
	
}


/** Edit June 2009 S.G.
Added function to do an AJAX edit of the registry label
**/
var orig_txt;

function doEditRegName(){
	var span = this;
	span.onclick = null;
	var rid = parseInt(span.id.replace("regName", ""));
	//replace the text in the span with an input that has the text as the value
	//also need a save (and cancel) button
	orig_txt = span.childNodes[0].nodeValue;
	var img = document.createElement("img");
	img.src = WEBROOT + "img/disk.png";
	var input = document.createElement("input");
	input.type= "text";
	input.value = orig_txt;
	span.removeChild(span.childNodes[0]);
	span.appendChild(input);
	span.appendChild(img);
	img.onclick = saveNewRegName;
}
function saveNewRegName(ev){
	if(ev){
		//FF, opera, safari, netscape
		ev.preventDefault();
		ev.stopPropagation();
	}else{
		//IE
		ev = window.event;
		ev.returnValue = false;
		ev.cancelBubble = true;
	}
	var img = this;
	var span = this.parentNode;
	this.onclick = null;
	var new_txt = span.getElementsByTagName("input")[0].value;
	var rid = parseInt(span.id.replace("regName", ""));
	span.removeChild(span.getElementsByTagName("input")[0]);
	span.removeChild(this.parentNode.getElementsByTagName("img")[0]);
	//call AJAX function to save the new label then restore the span to it's original state.
	
	//alert('rid=' + rid + '&txt=' + new_txt);
	//we can add sqlerr=1 to this to get the mysql error returned as part of the message
	$.ajax({
		   type:'POST',
		   url: WEBROOT + 'updateRegName.php',
		   data: 'rid=' + rid + '&txt=' + new_txt,
		   dataType:'xml',
		   success: function(ret, textStatus){
			   	//alert(ret.responseXML);
			    var msg = ret.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
			    var errCode = ret.responseXML.getElementsByTagName("errCode")[0].firstChild.nodeValue;
				if( parseInt(errCode) == 0){
			    	span.appendChild(document.createTextNode(new_txt));
					span.onclick = doEditRegName;
					return false;
				}else{
					alert(msg);
					span.appendChild(document.createTextNode(orig_txt));
					span.onclick = doEditRegName;
					return false;
				}
		   },
		   error: function(req, textStatus, errorThrown){
			    var x = req.responseXML;
			    if(x.getElementsByTagName("message")[0]){
					var msg = x.getElementsByTagName("message")[0].firstChild.nodeValue;
					alert(msg);
		   		}else{
					alert('Unable to save the new label at this time.');	
				}
			    span.appendChild(document.createTextNode(orig_txt));
				span.onclick = doEditRegName;
				return false;
		   }
	});
	
}


function fieldClear(obj, strDefault){
	if(obj.value==strDefault || strDefault == null)
		obj.value='';	
}

var newListRequested = false;
//var firstProductEntry = '<option value="0">No matching products yet</option>';
var strKeyWord = '';
var myInterval;

function productAdmin(){
	//this function runs at load on the product admin page
	//if there is a product key then run the function to populate the drop down list
	if(document.listForm.prodKey.value != ''){
		newListRequested = true;
		adminProductFetch(WEBROOT + 'admin/gen.products.php');
	}
	//also start the interval function for checking for changes in the keyword field
	myInterval = setInterval('checkKeyWords()', 500);
}

function checkKeyWords(){
	if(document.listForm.prodKey.value.length > 3){
		//we have four or more letters in the 	
		if(document.listForm.prodKey.value != strKeyWord){
			//update the keyword
			strKeyWord = document.listForm.prodKey.value.toString();
			//call the function to get the list
			if(!newListRequested){
				//set the test variable to true
				newListRequested = true;
				adminProductFetch(WEBROOT + 'admin/gen.products.php', strKeyWord);
			}
		}
	}
}

function createRequestObj(msg){
	//send an empty string or a failure message
	try{
		request = new XMLHttpRequest();
	}catch (tryMS){
		try{
			request = new ActiveXObject("Msxml2.XMLHTTTP");
		}catch( otherMS){
			try{
				request = new ActiveXOject("Microsoft.XMLHTTP");	
			}catch (failed){
				request = null;
			}
		}
	}
	
	if(request == null){
		//send back an alert if desired
		if(msg != ''){
			alert(msg);
		}
		return false;
	}else{
		return request;
	}
}

function adminProductFetch(url, key){
	//get the list of products from gen.products.php
	url = url + '?keyword=' + key;
	prodXML = createRequestObj('');
	if(prodXML){
		prodXML.open("GET", url, true);
		prodXML.onreadystatechange = function(){
			if(prodXML.readyState == 4){
				//a new list can be requested now
				newListRequested = false;
				//var jsonData = prodXML.responseText.toJSONString();
				strReturned = prodXML.responseText;
				//document.getElementById("output").innerHTML = strReturned;
				//alert(strReturned);
				var jsonData = eval( '(' + strReturned + ')' );
				populateList(jsonData);
			}
		};
		prodXML.send(''	);
	}
}

function populateList(data){
	document.getElementById("output").innerHTML =data.products.length + " product(s) in list";
	selectObj = document.listForm.products;
	selectObj.length = 0;
	numProducts = data.products.length;
	if(numProducts > 0){
		for(i=0; i < numProducts; i++ ){
			opt = document.createElement("option");
			//document.getElementById("cont").appendChild(document.createTextNode());
			var nm = data.products[i]['name'];
			nm = nm.replace('&quot;', '\u0022');	
			opt.text = nm + ' : ' + data.products[i]['sku'];
			opt.value = data.products[i]['id'];
			if(data.products[i]['id'] == loadedProduct){
				opt.selected = true;
			}
			try{
				selectObj.add(opt);
			}catch(e){
				selectObj.add(opt, null);
			}
		}
	}else{
		//only put back the original item
		opt = document.createElement("option");
		opt.text = 'No matching products yet';
		opt.value = 0;
		try{
			selectObj.add(opt);
		}catch(e){
			selectObj.add(opt, null);
		}
	}	
}

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

function getPosition(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e     = e.offsetParent;
	}

	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

	return {x:left, y:top, tn:e.tagName.toLowerCase()};
}


function getUpperLeftCorner(obj){
	var left = 0;
	var top = 0;
	//alert(obj.parentNode.parentNode.tagName);
	//alert(obj.parentNode.parentNode.offsetParent);
	while(obj.tagName.toLowerCase() != "td"){
		obj = obj.parentNode;
	}
	while (obj.offsetParent){
		left += obj.offsetLeft + (obj.currentStyle?(parseInt(obj.currentStyle.borderLeftWidth)).NaN0():0);
		top  += obj.offsetTop  + (obj.currentStyle?(parseInt(obj.currentStyle.borderTopWidth)).NaN0():0);
		obj     = obj.offsetParent;
	}
	left += obj.offsetLeft + (obj.currentStyle?(parseInt(obj.currentStyle.borderLeftWidth)).NaN0():0);
	top  += obj.offsetTop  + (obj.currentStyle?(parseInt(obj.currentStyle.borderTopWidth)).NaN0():0);
	
	return {x:left, y:top, tn:obj.tagName.toLowerCase()};
}

//Function for creating the popup for the catalogue page
function setHovering(){
	//whenever someone hovers over an anchor with the class hoverAnchor then the div inside with the class "full" will appear
	//alert('Hovering');
	allAnchors = document.getElementsByTagName("a");
	//loop through each to find the thumb and the full 
	for(a=0; a<allAnchors.length; a++){
		if(allAnchors[a].className == 'hoverAnchor'){
			//productAnchors.push(allAnchors[a]);
			allAnchors[a].onmouseover=function(){
				//alert(this.parentNode.tagName); - TD
				var images = this.getElementsByTagName("img");
				//var pos = getUpperLeftCorner(images[1]);
				var pos = getPosition(this);
				//strOutput = pos.tn + ': x-' + pos.x + ', y-' + pos.y;
				//document.getElementById("output").innerHTML = strOutput;
				var top = pos.y;
				var left = pos.x;
				images[0].style.top = top + "px";
				images[0].style.left = left + "px";
				images[0].style.display='block';
			}
			allAnchors[a].onmouseout=function(){
				//alert(this.tagName);	
				var images = this.getElementsByTagName("img");
				images[0].style.display='none';
			}
		}
	}
}

function setAddresses(){
	//check for safari and flip the email addresses as required.	//	
	if((navigator.userAgent.toLowerCase().indexOf("safari") != -1) || 
		((navigator.userAgent.toLowerCase().indexOf("opera") != -1)&& parseFloat(navigator.appVersion) < 8.0 )){
		//alert("Opera");
		//this is Safari
		allAnchors = document.getElementsByTagName("span");
		for(a=0; a<allAnchors.length; a++){
			if(allAnchors[a].className == 'rev'){
				strBackwards = allAnchors[a].innerHTML;
				//alert(strBackwards);
				sbLen = strBackwards.length-1;
				newAddress = '';
				for(b=sbLen; b>=0; b--){
					newAddress += strBackwards.substr(b, 1);
				}
				allAnchors[a].innerHTML = newAddress;
			}
		}
	}
}

function adminAddProductEdit(list){
	//depending on the className of the selected item in the list we will add a new form element to the td FormElement
	var type = list.options[list.selectedIndex].className;
	var nm = list.value;
	var theTD = document.getElementById('FormElement');
	var inputs = document.getElementsByTagName('input');
	var selects = document.getElementsByTagName('select');
	var textareas = document.getElementsByTagName('textarea');
	for(i=theTD.childNodes.length-1; i>=0; i--){
		theTD.removeChild(theTD.childNodes[i]);	
	}
	
	switch(type){
		case 'Tbox':
			var elm = document.createElement('input');	
			break;
		case 'Tarea':
			var elm = document.createElement('textarea');
			break;
		case 'ddList':
			var elm = document.createElement('select');
			break;
		default:
			//do nothing except remove the element
			return false;
	}
	elm.name = nm;
	elm.className = 'wide';
	//if it is a drop down list then we need to fetch the list from the server....
	theTD.appendChild(elm);
	if(elm.tagName.toLowerCase() == 'select'){
		//use jquery to fetch the list for brands, suppliers, categories or units
		$.post("returnlist.php", {"field": nm}, function(data){populate(data, elm);});
	}
}

function challenge(){
	//if the user is logged in then this function will run 10 minutes after the page is accessed.
	alert('You are about to be logged out because \nyou have exceeded the allowed time to be logged in \nwithout interacting with the site.');
	logout();
}

function populate(data, listObj){
	//add all the JSON data from "data"	into listObj
	//alert(data);
	JSON = eval('(' + data + ')');
	//alert(JSON.opts.length);
	for(i=0; i < JSON.opts.length; i++){
		var opt = document.createElement("option");
		opt.text = JSON.opts[i].lbl;
		opt.value = JSON.opts[i].id;
		try{
			listObj.appendChild(opt);
		}catch(e){
			listObj.add(opt);	
		}
	}
}


