// JavaScript Document

var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isAndroid = navigator.userAgent.match(/Android/i) != null;


function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else
		var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ')
			c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",-1);
}


// set and get objects stored in localStorage
Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return (value && JSON.parse(value));
}

function setHomePageDivs (d) {
	if (d.divData_width)
		$("#divData").width (d.divData_width);
	if (d.footer_height)
		$("#footer").height (d.footer_height);

	$("#divData").html (d.divData);

	if (d.divOnTheSide)
		$("#divOnTheSide").html (d.divOnTheSide);
	if (d.menu)
		$("#menu").html (d.menu);
}

// ***********************************************************
//	desc: get the value of a page 
// ***********************************************************
function getParameterByName( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}



// ***********************************************************
// Name: Display previous page
// Description: This subsystem allows the developer to create
//		store a page for easy future retrieval. The main
//		drawback to AJAX is that the brower's back button will
//		take the visitor completely out of the current page.
//		To remedy this, we maintain our own internal navigation.
//
//		This system revolves around an array called:
//			aDataInnerHTML
//		It also takes advantage of the fact that most successful
//		AJAX will replace the html in divData.  Before that happens
//		we issue the following call:
//
//		aDataInnerHTML.unshift (new oHistory ($("divData").innerHTML, fn));
//	
//		aDataInnerHTML is an array that contains previous html code
//		of a callback function for the previous page.  The above
//		line will create a new oHistory object and will store either the
//		current html in divData and optionally a callback function.
//		When an AJAX returns successfuly and results in a new
//		body for divData (this is the container where we place
//		all the pages from AJAX calls)
//			
// Arguments: szIn - The input string
// Return: A string without the commas
// ***********************************************************
var aHistory = new Array ();	// holds previous page or callback
var bCalledFromBackFromPreviousPage = true;
var aFields;

function oHist (opts) {

	if (opts.innerHTML) {
		this.innerHTML = opts.innerHTML;
		this.inputFlds = $(':input').each(function (i, e) { return ;});

		if (opts.sidebarHTML)
			this.sidebarHTML = opts.sidebarHTML;
	}
	if (opts.callback) {
		this.callback = opts.callback;
		if (opts.arg)
			this.arg = opts.arg;
	}
}

function DoesPreviousPageExist () { return ((aHistory.length) ? true : false); }

function BackFromPreviousPage () {
	if (aHistory.length) {
		var o = aHistory.shift();
		if (o.innerHTML) {
			aFields = o.inputFlds;
			$("#divData").html (o.innerHTML);
			// set the data
			$(':input').each(
				function (i, e) {
					if (e.type == "text"  ||  e.type == "textarea")
						e.value = aFields[i].value;
					else if (e.type == "radio"  ||  e.type == "checkbox")
						e.checked = aFields[i].checked;
					else if (e.type == "select-one")
						e.selectedIndex = aFields[i].selectedIndex;
				}
			);
			if (o.sidebarHTML)
				$("#divOnTheSide").html (o.sidebarHTML);
		}
		if (o.callback) {
			if (o.arg)
				o.callback(o.arg);
			else
				o.callback(bCalledFromBackFromPreviousPage);
		}
	}
}


// ***********************************************************
// Name: stripCommas
// Description: Removes the commas from a string.
// Arguments: szIn - The inpute string
// Return: A string without the commas
// ***********************************************************
function stripCommas (szIn) {
	var szOut = "";
	if (szIn) {
		for (i = 0; i < szIn.length; i++)
			if (szIn.charAt(i) != ",")
				szOut = szOut + szIn.charAt(i);
	}
	return szOut;
}

// ***********************************************************
// Name: convertDateFromSQL
// Description: Format a date for SQL insertion 
// Arguments: szIn - The date
// Return: A date formatted for 
// ***********************************************************
function convertDateForSQL (szIn) {
	if (typeof szIn == "undefined")
		return ("1969-12-23 00:00:00");

	if (szIn == "")
		return "";

	var a = szIn.split (/[ -./]/);
	return (a[2] + "-" + a[0] + "-" + a[1] + " 00:00:00");
}


// ***********************************************************
// Name: getMMDDYYYYFromSQL
// Description: Format a date for SQL insertion 
// Arguments: szIn - The date
// Return: A date formatted for 
// ***********************************************************
function getMMDDYYYYFromSQL (szIn) {
	var a = szIn.split (/[ -./]/);
	return (a[1] + "/" + a[2] + "/" + a[0]);
}


// ***********************************************************
// Name: formatNumberWithCommas
// Description: Format a string with a sepearator (i.e. 1,234,5678) 
// Arguments: num - The number that is to be formatted.
//		 dp - The number of decimal points in the number
//		 sepString - The seperator to use in the formatted string.
// Return: The number as a formatted string.
// ***********************************************************
function formatNumberWithCommas(num,dp,sepString) {
	var str = "";

	if (!dp)
		dp = 2;
	if (!sepString)
		sepString=",."
	if (dp)
		num=Math.round(num*Math.pow(10,dp))
	try {
		if (num == 0) {
			str = "0" + sepString.charAt(1)
			while (dp-- > 0)
				str += "0";
		} else {
			num=num.toString()
			str=sepString.charAt(1)+num.substr(num.length-dp)
			num=num.substr(0,num.length-dp)
			while (num.length>3) {
				str=sepString.charAt(0)+num.substr(num.length-3)+str
				num=num.substr(0,num.length-3)
			}
			str=num+str
		}
	} catch (e) {
		str = "";
	}
	return str;
}


// ***********************************************************
// Name: getXMLDocument
// Description: Get the xml document.  This will handle
//				IE and other browsers.
// Arguments: none
// Return: The xml document.
// ***********************************************************
function getXMLDocument () {
	try {
		return (new ActiveXObject('Microsoft.XMLDOM')); 
	} catch (e) {
		// not IE
		return  (document.implementation.createDocument('', 'root', null)); 
	}
}

// ***********************************************************
// Name: getSerializedData
// Description: Convert DOM subtree or DOM document into text
// Arguments: The xml documednt
// Return: The xml code as text.
// ***********************************************************
function getSerializedData (xmlDocument) {
	var szRet = "";
	if (String(xmlDocument.xml) != "undefined")
		szRet = '<?xml version="1.0" encoding="ISO-8859-1"?>' + xmlDocument.xml;
	else {
		  // create serializer object
		var xmlSerializer = new XMLSerializer();
		// serialize
		szRet = xmlSerializer.serializeToString(xmlDocument);
	}
	return (szRet);
}


// ***********************************************************
// Name: createXMLCdataNode
// Description: Create a CDATA node
// Arguments: xmlNode - The xml node
//				szNodeName - The name of the xml node
//				szNodeValue - The value to put into the node
// Return: none
// ***********************************************************
function createXMLCdataNode (xmlDocument, szNodeName, szNodeValue) {
	var el = xmlDocument.createElement(szNodeName);
	var newCDATA = xmlDocument.createCDATASection (szNodeValue);
	el.appendChild (newCDATA);
	xmlDocument.documentElement.appendChild (el);
}



// ***********************************************************
// Name: createSubXMLCdataNode
// Description: Create a CDATA node
// Arguments: xmlDocument - The xml document
//				xmlNode - The xml node
//				szNodeName - The name of the xml node
//				szNodeValue - The value to put into the node
// Return: none
// ***********************************************************
function createSubXMLCdataNode (xmlDocument, xmlNode, szNodeName, szNodeValue) {
	var el = xmlDocument.createElement(szNodeName);
	var newCDATA = xmlDocument.createCDATASection (szNodeValue);
	el.appendChild (newCDATA);
	xmlNode.appendChild (el);
}

function html2entities(){
	var re=/[(<>"'&]/g
	for (i=0; i<arguments.length; i++)
		arguments[i].value=arguments[i].value.replace(re, function(m){return replacechar(m)})
}

function replacechar(match){
	if (match=="<")
		return "&lt;"
	else if (match==">")
		return "&gt;"
	else if (match=="\"")
		return "&quot;"
	else if (match=="'")
		return "&#039;"
	else if (match=="&")
		return "&amp;"
}

// return the number as a zero filled 2 character number
function returnTwoDigits (n) {
	szTemp = "" + n;
	if (szTemp.length == 1)
		return ("0" + szTemp);
	else
		return (szTemp);
}


// trim the surrounding spaces from a string
function trim11 (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}


// this function will accept date input from the user in different forms
//	and will return a valid date suitable for SQL (i.e. yyyy-mm-dd)
// the input can be delimited by a space, dash, period or forward slash
// the input can be in the form of mm/dd/yyyy, m/d/yyyy, m/d/yyyy,
//	mmddyy, yyyy/mm/dd or yyyy/m/d
// if 4 digits are provided then the date is assumed to be mmdd in the current
//	year
// if 1 or 2 digits are provided, then the day of the month is assumed.  if the
//	day is greater than today's date, then the date is assumed to be in the future.
//	if less then today's date, then the date is assumed to be in the past.
// if the input is in the form mm/dd or m/d then the current year is assumed.
function getValidDate (szDate) {
	szDate = trim11(szDate);
	var nLen = szDate.length;
	var szRet = "";
	var mm;
	var dd;
	var yyyy;
	var a = szDate.split (/[ -./]/);
	if (a.length >= 3) {
		if (a[0] > 1900 &&  a[0] < 2099)		// assume YYYY/mm/dd
			szRet = a[0] + "-" + returnTwoDigits(a[1]) + "-" + returnTwoDigits(a[2]);
		else if (a[2] > 1900 &&  a[2] < 2099)		// assume mm/dd/YYYY
			szRet = a[2] + "-" + returnTwoDigits(a[0]) + "-" + returnTwoDigits(a[1]);
		else {
			if (a[2].length == 2)
				a[2] = "20" + a[2];
			else if (a[2].length == 0) {
				var d = new Date();
				a[2] = d.getFullYear ();
			}
		}
	} else if (a.length == 2) {
		var d = new Date();
		szRet = d.getFullYear () + "-" + returnTwoDigits(a[0]) + "-" + returnTwoDigits(a[1]);
	} else if (nLen == 8) {	// date is either mmddYYYY  or YYYYmmdd
		yyyy = szDate.substr (0, 4);
		if (yyyy > "1900" &&  yyyy < "2099")		// assume YYYY/mm/dd
			szRet = yyyy + "-" + szDate.substr(4, 2) + "-" + szDate.substr(6, 2);
		else {
			yyyy = szDate.substr (4, 4);
			if (yyyy > "1900" &&  yyyy < "2099")		// assume YYYY/mm/dd
				szRet = yyyy + "-" + szDate.substr(0, 2) + "-" + szDate.substr(2, 2);
		}
	} else if (nLen == 6) { // date is either mmddyy or yymmdd or yyyymm
		yyyy = szDate.substr (0, 4);
		if (yyyy > "1900" &&  yyyy < "2099")		// assume YYYYmm
			szRet = szDate;
		else {
			a[0] = szDate.substr (0,2);
			a[1] = szDate.substr (2,2);
			a[2] = szDate.substr (4,2);
			if (
				isValidMonth (a[0])  &&
				isValidDay (a[1])  &&
				isValidYear (a[2])
			)
				szRet = "20" + a[2] + "-" + a[0] + "-" + a[1];
			else if (
				isValidMonth (a[1])  &&
				isValidDay (a[2])  &&
				isValidYear (a[0])
			)
				szRet = "20" + a[0] + "-" + a[1] + "-" + a[2];
		}
	} else if (nLen == 4) {	// date is mmdd for the current year
		var d = new Date();
		szRet = d.getFullYear () + "-" + returnTwoDigits(parseInt(szDate.substr (0, 2))) + "-" + returnTwoDigits(szDate.substr (2,2));			
	} else if (nLen == 1 ||  nLen == 2) {	// date is d or dd and refers to the next date
											//	with that as the day of the month
		var d = new Date();
		var nYear = d.getFullYear ();
		var nMonth = d.getMonth ();
		var nDate = parseInt (szDate);

		if (nDate < d.getDate()) {		// the date has passed, set to the next month
			nMonth++;
			if (nMonth > 11) {
				nMonth = 0;
				nYear++;
			}	
		}
		szRet = nYear + "-" + returnTwoDigits(nMonth+1) + "-" + returnTwoDigits(nDate);			
	} else {
		szRet = "nLen = " + nLen;
	}
	return (szRet);
}

function gup ( name ) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return null;
	else
		return results[1];
}


function Logout () {
	$.post(
		"irvprem_backend.php",
		{ "ActionToPerform": "Logout" },
		function(d){
			$("#frm").attr("target", "_self")
			$("#frm").attr("action", "logon.php")
			$("#frm").submit();
		},
		"json"
	);
}

function SwitchAccounts () {
	$.post(
		"irvprem_backend.php",
		{ "ActionToPerform": "SwitchAccounts" },
		function(d){
			aHistory.unshift (new oHist ({innerHTML: $("#divData").html()}));
			setHomePageDivs (d);
		},
		"json"
	);
}

function getValidInteger (n) { return ((isNaN(n)||n=="")?0:parseInt(n)); }
function getValidFloat (n) { return ((isNaN(n)||n=="")?0.0:parseFloat(n)); }
function getValidNumber (n) { return ((isNaN(n)||n=="")?0:n); }

// Show a custom alert box that is built on colorbox
// The first argument is the message to be displayed
// The second argument is an object that can contain:
//	ofld - The field where we will set the focus
//			after the alert box is dismissed
//	redirect - A URL that the visitor will be sent to
//				after the alert box is dismissed.
function ShowCustomAlertBox (szMessage, opts) {
	szWidth = ((opts.width) ? opts.width : 250) + "px";
	$("#divAlertMessage").html (szMessage);
	$.colorbox({
		width:szWidth,
		opacity:".60",
		inline:true,
		href:"#divAlert",
		onClosed: function () {
			if (opts.oFld)
				opts.oFld.focus ();
			if (opts.redirect) {
				$("#tagRedirect").attr("href", opts.redirect);
				$("#tagRedirect").click();
				window.location.href = $("#tagRedirect").attr("href");			}
		}
	});
}
// Ask the visitor for a date.
// The first argument is the message to be displayed
// The second argument is an object that can contain:
//	ofld - The field where we will set the focus
//			after the alert box is dismissed
//	redirect - A URL that the visitor will be sent to
//				after the alert box is dismissed.
function GetColorboxDate (szMessage, nOrderID) {
	$("#divColorboxDateMessage").html (szMessage);
	$.colorbox({
		width:"500px",
		opacity:".60",
		inline:true,
		href:"#divColorboxDate",
		onComplete: function () {
			var d = new Date();
			var curr_date = d.getDate();
			var curr_month = d.getMonth();
			var curr_year = d.getFullYear();
			szDate = (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear();
			$("#txtColorboxDate").val(szDate);
			$("#txtColorboxDate").datepicker();
		},
		onClosed: function () {
			var dJson = {
				"ActionToPerform": "CreateInvoiceFromOrder",
				"OrderID": nOrderID,
				"InvoiceDate": $("#txtColorboxDate").val()
			};
		
		
			$.post(
				"invoice_backend.php",
				dJson,
				function(d){
					$("#frm").attr("target", "_blank");
					$("#frm").attr("action", d.pdf);
					$("#frm").submit();
				},
				"json"
			);
		}
	});
}

/*
$('select.foo option:selected').val();    // get the value from a dropdown select
$('select.foo').val();                    // get the value from a dropdown select even easier
$('input:checkbox:checked').val();        // get the value from a checked checkbox
$('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons
*/
