// main.js

/*
 *	Contains all the general functions that I might need
 */

// Global Variables
var date_format='yyyy-MM-dd';//MySQL default 


// Get Element By Id
function getEl(id) {
	return document.getElementById(id);
}

// Get the Event
function getEvent(e){
	if (!e){
		return window.event;
	}
	return e;
}
// Get the Element the event happened on
function getEventEl(e){
	var evt=getEvent(e);
	if(evt.srcElement){
		return evt.srcElement;
	}
	else if(evt.target){
		return evt.target;
	}
	else {
		return null;
	}
}

// Get the X position of the mouse
function getMouseX(e){
	if (e.pageX) 	{
		return e.pageX;
	}
	else if (e.clientX) 	{
		return (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft);
	}
}
// Get the Y position of the mouse
function getMouseY(e){
	if (e.pageX) 	{
		return e.pageY;
	}
	else if (e.clientY) 	{
		return (e.clientY + document.body.scrollTop + document.documentElement.scrollTop);
	}
}
// Get the width of an element
function getWidth(el){
	return el.offsetWidth;
}
// Get the height of an element
function getHeight(el){
	return el.offsetHeight;
}
/*
 * Returns size of element:
 * [Width, Height]
 */
function findSize(el){
	return [el.offsetWidth,el.offsetHeight];
}

/**
 * Returns a array with 4 object coordinates
 * [Left, Top, Right, Bottom]
 */
function findPos(obj) {
	var curleft =0;
	var curtop = 0;
	var dims=findSize(obj);
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj.offsetParent) {
			obj = obj.offsetParent;
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop,(curleft+dims[0]),(curtop+dims[1])];
}

/**
 * Sets 4 variables in the object
 * [Left, Top, Right, Bottom]
 */
function setCoordinates(obj) {
	var origObj=obj;
	var curleft=0;
	var curtop = 0;
	var dims=findSize(obj);
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj.offsetParent) {
			obj = obj.offsetParent;
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	origObj.LEFT=curleft;
	origObj.TOP=curtop;
	origObj.RIGHT=curleft+origObj.offsetWidth;
	origObj.BOTTOM=curtop+origObj.offsetHeight;
}

// Get the left and the top of the element.
function getLeft(el) {
	var tmp = el.offsetLeft;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetLeft;
		el = el.offsetParent;
	}
	return tmp;
}
function getTop(el) {
	var tmp = el.offsetTop;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetTop;
		el = el.offsetParent;
	}
	return tmp;
}


function getScrollLeft(){
	if (document.documentElement)
	{
		return document.documentElement.scrollLeft;
	}
	else if (document.body)
	{
		return document.body.scrollLeft;
	}
}
function getScrollTop(){
	if (document.documentElement)
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body)
	{
		return document.body.scrollTop;
	}
}
function getClientW(){
	if(document.innerWidth){ 
		return document.innerWidth;
	} else if(document.documentElement.clientWidth){ 
		return document.documentElement.clientWidth;
	} else if(document.body){ 
		return document.body.clientWidth; 
	}
}
function getClientH(){
	if(document.innerHeight){ 
		return document.innerHeight;
	} else if(document.documentElement.clientHeight){ 
		return document.documentElement.clientHeight;
	} else if(document.body){
		return document.body.clientHeight; 
	}	
}


/****************************************************
 *													*
 *				Display functions					*
 *													*
 ****************************************************/

/*
 * Takes a div ID
 * Sets its display to 'block'
 * Thus opening it
 */
function openDiv(div){
	block(getEl(div));
}
/*
 * Takes a div ID
 * Sets its display to 'none'
 * Thus closing it
 */
function closeDiv(div){
	none(getEl(div));
}

/*
 * Takes an element ID
 * Sets its display to ''
 * Thus opening it
 */
function showElement(elementID){
	reset(getEl(elementID));
}
/*
 * Takes a div ID
 * Sets its display to 'none'
 * Thus closing it
 */
function hideElement(elementID){
	none(getEl(elementID));
}

// Display and visibility functions
function block(element){
	element.style.display='block';
}
function inline(element){
	element.style.display='inline';
}
function none(element){
	element.style.display='none';
}
function visible(element){
	element.style.visibility='visible';
}
function hidden(element){
	element.style.visibility='hidden';
}
function reset(element){
	element.style.display='';
}


//change the opacity for different browsers
function changeOpac(id,opacity) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}




/****************************************************/
/**
 * Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
 */
function luhnCheck(cardNumber) {
    if (isLuhnNum(cardNumber)) {
        var no_digit = cardNumber.length;
        var oddoeven = no_digit & 1;
        var sum = 0;
        for (var count = 0; count < no_digit; count++) {
            var digit = parseInt(cardNumber.charAt(count));
            if (!((count & 1) ^ oddoeven)) {
                digit *= 2;
                if (digit > 9) {digit -= 9;}
            }
            sum += digit;
        }
        if (sum == 0) {return false;}
        if (sum % 10 == 0) {return true;}
    }
    return false;
}

function isLuhnNum(argvalue) {
    argvalue = argvalue.toString();
    if (argvalue.length == 0) {
        return false;
    }
    for (var n = 0; n < argvalue.length; n++) {
        if ((argvalue.substring(n, n+1) < "0") ||
            (argvalue.substring(n,n+1) > "9")) {
            return false;
        }
    }
    return true;
}

function formatCurrency(p) {
	num = p.value.toString().replace(/\$|\,/g,'');
	num= isNaN(num) ? "0" : num;
	num = Math.floor(Math.abs(num)*100+0.50000000001);
	cents = num%100;
	cents = (cents<10) ? ("0" + cents) : cents;
	num = Math.floor(num/100).toString();
	p.value=num + '.' + cents;
}

function taLimit(evt,textarea,limit,countID) {
	var e=window.event ? window.event : evt;
	var unicode=e.charCode ? e.charCode : e.keyCode;
	if (textarea.value.length>=limit*1 && unicode!=8){ 
		return false;
	}
	else { 
		return true;
	}
}
function taCount(textarea,limit,countID) {
	//incase there is a paste
	if(textarea.value.length>=limit*1){textarea.value=textarea.value.substring(0,limit);}
	document.getElementById(countID).innerHTML=(limit*1)-textarea.value.length;
}



function moveToAnchor(anchor){
	if(anchor!='null'&&anchor!=''){
		document.location='#'+anchor;
	}
}
function setAnchor(anchor){
	document.forms[0].elements['anchor'].value=anchor;
}

function setAnchorLink(link,anchor){
	link.href+=("&anchor="+anchor);
}


function fixImgs(whichId, maxW) {
	if(document.getElementById(whichId)){
		var pix=document.getElementById(whichId).getElementsByTagName('img');
		for (i=0; i<pix.length; i++) {
			w=pix[i].width;
			h=pix[i].height;
	    	if (w > maxW) {
	      		f=1-((w - maxW) / w);
	      		pix[i].width=w * f;
	      		pix[i].height=h * f;
	    	}
	  	}
	}
}

/**************************
	Disables an element
	t=The element name
**************************/
function dis(t){
	document.forms[0].elements[t].value="";
	document.forms[0].elements[t].disabled=true;
}

/**************************
	Enables an element
	t=The element name
**************************/
function en(t){
	document.forms[0].elements[t].disabled=false;
}


/**************************
	Autofill an element
	input=The element holding the value you want to use
	output=The element id you want to fill in
**************************/
function autoFill(input,output){
	if(opener){
		opener.document.getElementById(output).value=input.value;
	}
	else{
		document.getElementById(output).value=input.value;
	}
}

function myOpen(url){
      var newwindow='';
      newwindow=window.open(url,'','location=0,status=0,resizable=0,scrollbars,menubar=0,toolbar=0,height=500,width=825,top=0,left=0');
      //sets popup opener to the main window
      if (!newwindow.opener) {newwindow.opener = self;}
      return false;
}


/*function launchwin(winurl,winname,winfeatures){
	remote = window.open("",winname,winfeatures);
	remote.location.href = winurl;
	if (remote.opener == null) remote.opener = window;
	remote.opener.name = "Body";

}*/

function selectforcopy(obj){
	var s = window.getSelection();
	s.removeAllRanges();
	var range = document.createRange();
	range.selectNodeContents(obj);
	s.addRange(range);
}

function pause(millis){
	var date = new Date();
	var curDate = new Date();

	while(curDate-date < millis){
		curDate = new Date();
	}
} 


function loadJS(url)
{
   var e = document.createElement("script");
   e.src = url+'.js';
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e);
}
function loadCSS(url)
{
   var e = document.createElement("link");
   e.href = url+'.css';
   e.type="text/css";
   e.rel="stylesheet";
   document.getElementsByTagName("head")[0].appendChild(e);
}

function validateRetype(obj1ID,obj2,field){
	var obj1=getEl(obj1ID);
	if(obj1.value!=obj2.value){
		alert(field+" fields do not match.");
	}
}
/**
     * Trims a string.
     *
     * @method _trim
     * @param {string} str The string to be trimmed.
     * @return {string} The trimmed string
     * @private
     */
    function trim(str) {
        return str.replace( /^\s*(\S*(\s+\S+)*)\s*$/, "$1" );
    }
