/*
---------------------------------------------------------------------------------------------------
CORE JS FUNCTIONS

All standard core js dependencies

---------------------------------------------------------------------------------------------------
*/

// WINDOW DIMENSIONS  --  REDUNDANT  --
// Detects window size (downloaded)
function CORE_windowDimensions(answer) {
	var screenWidth = 0, screenHeight = 0;

	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		screenWidth = window.innerWidth;
		screenHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		screenWidth = document.documentElement.clientWidth;
		screenHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		screenWidth = document.body.clientWidth;
		screenHeight = document.body.clientHeight;
	}

	if (answer == 'width')	{
		return screenWidth;
	}

	if (answer == 'height')	{
		return screenHeight;
	}
}



// WINDOW/DOCUMENT SIZES
var windowProps = new Array(
	'clientHeight',
	'clientWidth',
	'scrollHeight',
	'scrollWidth',
	'scrollLeft',
	'scrollTop',
	'offsetHeight',
	'offsetWidth'
);

function CORE_windowProperties(property){

	returnArray = new Array();

	for (var i=0; i<windowProps.length;i++)	{
		returnArray[windowProps[i]] = document.body[windowProps[i]];
	}

	return (returnArray[property]);
}


// COOKIES
// Set of cookie functions (downloaded)

// create cookie
function CORE_cookieCreate(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=/";
}


// read cookie
function CORE_cookieRead(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;
}


// delete cookie
function CORE_cookieDelete(name) {
	CORE_cookieCreate(name,"",-1);
}



// AJAX
// standard ajax function (downloaded)

// request, called by the application
function sendRequest(url, params, callback, target_id, method, load_id, loadergif) {
//alert(url);
//alert(params);
//alert(callback);
//alert(target_id);
//alert(method);
//alert(load_id);

//alert(':url:'+url+'\n:params:'+params+'\n:target_id:'+target_id+'\n:method:'+method);

	if(load_id == true || load_id == undefined) {
		loadDIV = document.getElementById(target_id);
		loadgif = 'large';
		size	= 32;
	} else if (load_id != false) {
		loadDIV = document.getElementById(load_id);
		loadgif = 'small';
		size	= 16;
	}

	if (load_id != false) {
		loadPosLeft	= (loadDIV.style.width.substr(0,loadDIV.style.width.length-2) / 2) - (size / 2);
		loadPosTop	= (loadDIV.style.height.substr(0,loadDIV.style.height.length-2) / 2) - (size / 2);

		loadDIV.innerHTML = '<img style="position: relative; width: 16px; height: 16px; top: '+loadPosTop+'px; left: '+loadPosLeft+'px;" src="'+loadergif+'ajax_loader_'+loadgif+'.gif">';
	}

	if(method == 'GET') {
		open_url = url+'?'+params;
		postData = null;
	}
	if(method == 'POST') {
		open_url = url;
		postData = params;
	}

    var req = createXMLHTTPObject();
    if (!req) return;
    req.open(method,open_url,true);
    req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    if (postData)
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    req.onreadystatechange = function () {
        if (req.readyState != 4) return;
        if (req.status != 200 && req.status != 304) {
//            alert('HTTP error ' + req.status);
            return;
        }
        callback(req,target_id);
    }
    if (req.readyState == 4) return;
    req.send(postData);
}

// factories
var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

// XML object based on factory
function createXMLHTTPObject() {
    var xmlhttp = false;
    for (var i=0;i<XMLHttpFactories.length;i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}

// update the target
function handleRequest(req, target_id) {
    var writeroot			= document.getElementById(target_id);
    writeroot.innerHTML		= req.responseText;

	CORE_runScripts(document.getElementById(target_id));
}

// run scripts
function CORE_runScripts(e) {

	if (e.nodeType != 1) return; //if it's not an element node, return

	if (e.tagName.toLowerCase() == 'script') {
		eval(e.text); //run the script
	}

	var n = e.firstChild;
	while ( n ) {
		if ( n.nodeType == 1 ) CORE_runScripts( n ); //if it's an element node, recurse
		n = n.nextSibling;
	}
}



// FORM FOCUS
// Sets the focus to the first form field
function CORE_firstInputFocus() {
	var bFound = false;

	// for each form
	for (f=0; f < document.forms.length; f++){
		// for each element in each form
		for(i=0; i < document.forms[f].length; i++){
			// if it's not a hidden element
			if (document.forms[f][i].type == "text"){
				// and it's not disabled
				if (document.forms[f][i].disabled != true){
					// set the focus to it
					document.forms[f][i].focus();
					var bFound = true;
				}
			}
			// if found in this element, stop looking
			if (bFound == true)
			break;
		}
		// if found in this form, stop looking
		if (bFound == true)
			break;
	}
}



// DIV DISPLAY
// Toggle single DIV display
function CORE_divDisplay(div_id) {

	if (document.getElementById(div_id).style.display == 'block') {
		document.getElementById(div_id).style.display = 'none';
		return false;
	} else {
		document.getElementById(div_id).style.display = 'block';
		return true;
	}
}



// DIV COLLAPSE
// Toggle single DIV collapse with +/- image and save multiple to cookie
function CORE_divCollapse(div_id, div_class, trigger, img_dir, cookie) {

	if (CORE_divDisplay(div_id) == true){
		document.getElementById(div_id+'_'+trigger).src = img_dir+'minus.gif';
	} else {
		document.getElementById(div_id+'_'+trigger).src = img_dir+'plus.gif';
	}

	var openDivs = '';

	for(var x=0; x<divs.length; x++) {
		if(divs[x].className == div_class && divs[x].style.display == 'block') {
			openDivs = openDivs+divs[x].id+',';
		}
	}

	CORE_cookieCreate(cookie,openDivs,1);
}


// DIV SWITCH COLLAPSE
function CORE_divSwitch(div_id) {
	CORE_divDisplay(div_id+'_open');
	CORE_divDisplay(div_id+'_closed');
}


// ELEMENTS BY CLASSNAME
// Downloaded function that simulates elements by classname function
document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

// DIVS BY CLASSNAME
document.getDivsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('div');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

// SPANS BY CLASSNAME
document.getSpansByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('span');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

// IMAGE BY CLASSNAME
document.getImagesByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('img');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

// INPUT BY CLASSNAME
document.getInputsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('input');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	var elem = this.getElementsByTagName('select');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	var elem = this.getElementsByTagName('textarea');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};


// EMAIL CHECK
function CORE_emailCheck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false
	 }

	 if (str.indexOf(" ")!=-1){
		return false
	 }

	 return true
}


function CORE_bookmark(anchor){
	if(window.external){
		window.external.AddFavorite(anchor.getAttribute('href'), anchor.getAttribute('title'));
		return false;
	}
	return true;
}


// urlencoding
var urlstring = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


// CENTER POPUP
function CORE_popupWindow(page, windowname, w, h, scroll, orientation) {
	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(page, windowname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}