/****************************************************************************
*
* Copyright 2007 dynamIt Technologies, LLC.
*
* The following code is for the exclusive use of dynamIt Technologies, LLC.
* Any use of this code with written permission from dynamIt is prohibited.
*
* Report an abuse of this copyright to
*	dynamIt Technologies, LLC
*	300 Marconi Blvd. Suite 203
*	Columbus, Ohio 43215 USA
*	+1.614.538.0095
*
****************************************************************************/

/**************************************
* This will define markup for our default dialog
* box used in dynamIt__OnConfirm() and dynamItConfDialog()
**************************************/
function dialogTop(title) {
	if(!title) title = '';
	return '<div id="dialogPlate">';
}

function dialogBottom() {
	return '</div>';
}

/**************************************
* Some basic browser detection
**************************************/
var IE7 = false;
var IE6 = false;
var FF = false;
if (window.XMLHttpRequest) {
	if(document.epando){
		//IE7
		IE7 = true;
	}else{
		//mozilla, safari, opera, etc
		FF = true;
	}
} else {
	// IE6, older browsers
         IE6 = true;
}

/**************************************
* This method will initialize the dynamIt Ajax
* system by placing the
**************************************/
$(document).ready(function() {

	var pos = (IE6) ? "absolute" : "fixed";

	// create cover all div.
	$("<div></div>").prependTo("body").attr("id", "dynamItCoverAll").css({
		position: pos,
		width: "1px",
		height: "1px",
		top: "0px",
		left: "0px",
		backgroundColor: "#000044",
		display: "none",
		zIndex: "1000000",
		opacity: ".60",
		filter: "alpha(opacity=60)" });

	// create the popup "window"
	$("<div></div>").prependTo("body").attr("id", "dynamItPopUpWin").css({
		position: pos,
		width: "313px",
		height: "226px",
		display: "none",
		border: "0",
		zIndex: "1000002"});


	$("<div></div>").prependTo("#dynamItPopUpWin").attr("id", "dynamItPopUp");

	$("<div></div>").prependTo("body").attr("id", "dynamItSimpleLoading").css({
		color: "#194a78",
		fontSize: "11px",
		fontFamily: "Verdana, Tahoma, sans-serif",
		fontWeight: "bold",
		backgroundColor: "white",
		backgroundImage: "url(img/core/loader.gif)",
		backgroundRepeat: "no-repeat",
		backgroundPosition: "8px 8px",
		border: "1px solid #194a78",
		padding: "8px 8px 8px 32px",
		position: "absolute",
		display: "none",
		opacity: ".80",
		filter: "alpha(opacity=80)",
		zIndex: "1000004"
	});


});

/**************************************
* FIX IE 6 
**************************************/
var dialogOpen = false;
var dialogScroll = 0;
$(window).scroll(function() {

	if(IE6) {
		if(dialogOpen) {
			window.self.scrollTo(0, dialogScroll);
		}
	}

}).resize(function() {

	if(dialogOpen) {
		dynamItPositionDialog();
	}
});


function scrollY() {

        var scroll = 0;
        if(document.body.scrollTop) scroll = document.body.scrollTop;
        else if(document.documentElement.scrollTop) scroll = document.documentElement.scrollTop;
        else if(window.pageYOffset) scroll = window.pageYOffset;

        return scroll;
}


/**************************************
* This method and variables will allow for
* the capturing of the mouse position at any time
**************************************/
document.onmousemove = dynamItSetMouse;

var xmouse = 0;
var ymouse = 0;
function dynamItSetMouse(e) {
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		xmouse = e.pageX;
		ymouse = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		xmouse = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		ymouse = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

}

function dynamItMouse() {
	return { pageX: xmouse, pageY: ymouse };
}

function dynamItReload() {
	window.location.reload();
}

/**************************************
* This method and variables will allow for
* the capturing of the current window size.
**************************************/
function dynamItWindowSize() {
	var windowWidth;
	var windowHeight;

	if( typeof(window.innerWidth) == 'number' ) {
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	} else {
		windowWidth = screen.width;
		windowHeight = screen.height;
	}

	return {w: windowWidth, h: windowHeight};
}

/**************************************
* This method creates the object necessary to carry
* out an ajax request. This function will be used by
* the sendRequest and postRequest functions.
**************************************/
function dynamItXmlHttpObject(handler) {
	var objXMLHttp = null;

	if(window.XMLHttpRequest) {
		objXMLHttp = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	return objXMLHttp;
}


/**************************************
* This method will generate the necessary object
* and carry out the AJAX request via GET.
* url - the script url to execute.
* loadfcn - the function to be called on state change.
**************************************/
function dynamItSendRequest(url, loadfcn) {
	xmlHttp = dynamItXmlHttpObject();
	if(xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}

	xmlHttp.onreadystatechange = loadfcn;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}


/**************************************
* This method will generate the necessary object
* and carry out the AJAX request via POST.
* url - the script url to execute.
* data -  the url excoded data to send.
* loadfcn - the function to be called on state change.
**************************************/
function dynamItPostRequest(url, data, loadfcn) {
	xmlHttp = dynamItXmlHttpObject();
	if(xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}

	xmlHttp.onreadystatechange = loadfcn;
	xmlHttp.open("POST", url, true);
	xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(data);
}

/**************************************
* This method will return true if the given xmlHttp
* object has a readyState of 'complete'
**************************************/
function isComplete(xmlHttp) {
	return (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete");
}

/**************************************
* This method takes in a reference to an html element
* and returns the element obj. If the parameter passed
* is the object it self, it will simply return it back
* to the caller. Otherwise, this function will attempt
* to retrieve the element by ID. Thus, this method also
* serves as an alias for document.getElementById().
**************************************/
function dynamItElem(obj) {
    try {
        if(typeof(obj) == 'object')
            return obj;
        else
            return document.getElementById(obj);
    }
    catch(e) {
        return null;
    }
}


/************************************
* The following methods deal with the dynamIt AJAX
* dialog box.
************************************/
function dynamItOpenDialog(html, w, h) {

	if(IE6) {
		// fix IE6 for fixed positioning
		hideSelects();
		dialogScroll = scrollY();
	}

	dialogOpen = true;

	$("#dynamItPopUp").html(html);

	dynamItSizeDialog(w, h);
	dynamItPositionDialog();

	$("#dynamItCoverAll").fadeIn("slow");
	$("#dynamItPopUpWin").fadeIn("slow");

}

	// In IE6 select are always on top: this needs fixed
         var mySelects;
	function showSelects() {
		if(mySelects) {
			for(var i = 0; i < mySelects.length; i++) {
				mySelects[i].style.visibility = "visible";
			}
		}
	}
	function hideSelects() {
		mySelects = new Array();
		var sels = document.getElementsByTagName('select');
		for(var i = 0; i < sels.length; i++) {
			sels[i].style.visibility = "hidden";
			mySelects[mySelects.length] = sels[i];
		}
	}


function dynamItSizeDialog(w, h) {

	w = parseInt(w, 10);
	h = parseInt(h, 10);
	var wx = (isNaN(w) || w == 0) ? 'auto' : w + 'px';
	var hx = (isNaN(h) || h == 0) ? 'auto' : h + 'px';

	$("#dynamItPopUpWin").width(wx).height(hx);
	$("#dynamItCoverAll").width("100%").height("100%");

	if(IE6) {

		var win = dynamItWindowSize();
		$("#dynamItCoverAll").width(win.w).height(win.h);
	}

}

function dynamItResizeDialog(w, h) {
	return;

	var win = dynamItWindowSize();

	// calculate new width and height from params
	w = parseInt(w, 10);
	h = parseInt(h, 10);
	var wx = (isNaN(w) || w == 0) ? 'auto' : w + 'px';
	var hx = (isNaN(h) || h == 0) ? 'auto' : h + 'px';

	// get left and top based on new width and height
         var left = (win.w/2) - (w/2);
         var top = (h == 'auto') ? 150 : (win.h/2) - (h/2);
	if(IE6) top = top + dialogScroll;

	$("#dynamItPopUpWin").animate({
		top: top + 'px',
		height: hx
	}, {queue: true, duration: 1000}).animate({
		left: left + 'px',
		width: wx
	}, {queue: true, duration: 1000});
}

function dynamItPositionDialog() {

	var win = dynamItWindowSize();
	var w = $("#dynamItPopUpWin").width();
	var h = $("#dynamItPopUpWin").height();

         var left = (win.w/2) - (w/2);
         var top = (h == 'auto') ? 150 : (win.h/2) - (h/2);

	if(IE6) {
		top = top + dialogScroll;
		$("#dynamItCoverAll").css({ top: dialogScroll + 'px' });
	}

	$("#dynamItPopUpWin").css({
		left: left + 'px',
		top: top + 'px'
	});

}



function dynamItWaitDialog(message) {

	if(!message) message = '';

	var html = '';
	html += '<div style="padding: 30px; text-align:center;">';
	html += '	<img src="img/core/loader-big.gif" alt="Loading..." /><br />';
	html += message;
	html += '</div>';


	dynamItOpenDialog(html, 300, 160);

}

function dynamItConfDialog(message, cancel) {

	var html = '';
	html = dialogTop('&nbsp;');
	html += '	<div style="padding: 12px 12px 0 12px;">' + message + '</div>';
         html += '	<div style="text-align:center; padding: 12px;"><input type="button" value=" &nbsp; Ok &nbsp; " onclick="dynamItCloseDialog();" id="confOkButton" /></div>';
	html += dialogBottom();

	$("#dynamItPopUp").html(html);

	dynamItOpenDialog(html, 400, $("#dynamItPopUp").height());

	$("#confOkButton").focus();
}

var mdbTimeout = null;
function dynamItModelessDialog(message) {

	if(mdbTimeout) clearTimeout(mdbTimeout);

	var win = dynamItWindowSize();
         var left = (win.w/2) - (340/2);
	var top = 0;

	$('#dynamItmdb').fadeOut('fast', function() {
		$(this).css({"left":left, "top":top}).html(message).show();
	});

	mdbTimeout = setTimeout(function() {
		$('#dynamItmdb').fadeOut('slow');
	}, 5000);


}

function dynamItCloseDialog() {

	$("#dynamItCoverAll").fadeOut("slow");
	$("#dynamItPopUpWin").fadeOut("slow");

	if(IE6) {
		showSelects();
	}

	dialogOpen = false;

}


/**************************************
* These methods will open up a very simple loading
* box at the mouse position and then close it again
* when done.
**************************************/

function openSimpleLoading(str) {
	var e = dynamItMouse();
	$("#dynamItSimpleLoading").html(str).css({ left: e.pageX + 'px', top: e.pageY + 'px' }).show();
}


function closeSimpleLoading() {
	$("#dynamItSimpleLoading").hide();
}


/**************************************
* This method given a url will use AJAX to retrieve
* the output at that URL and load them into the
* specificed HTML element
**************************************/
function dynamItLoad(url, pane, w, h, callback) {

	var container = dynamItElem(pane);

	if(container) {
                 openSimpleLoading('Loading...');
	} else {
		dynamItOpenDialog('');
		dynamItWaitDialog();
	}

	dynamItSendRequest(url, function() {
		if(isComplete(xmlHttp)) {
			if(container) {
				closeSimpleLoading();
				$(container).html(xmlHttp.responseText);
			} else {
				dynamItOpenDialog(xmlHttp.responseText, w, h);
			}
			if(callback) { callback(); }
		}
	});

}


function dynamItLoadIfEmpty(url, pane, callback) {
	var loaded;
	pane = dynamItElem(pane);
	if($(pane).html().length == 0) {
		dynamItLoad(url, pane, null, null, callback);
		loaded = true;
	} else {
		loaded = false;
	}
	$(pane).show();
	return loaded;
}

function dynamItLoadDialog(url, w, h, scroll, callback) {
	dynamItLoad(url, null, w, h, callback);
}

/**************************************
* This method take as its parameter and ordinary
* HTML form object and submits it via AJAX
* The script run by the ajax needs to echo
* back a javascript function call and nothing else.
**************************************/
function dynamItPublish(f) {
	var url = f.action;
	var pageData = dynamItFormData(f);

	if (f.method.toUpperCase() == "POST") {
		dynamItPostRequest(url, pageData, function () {
			if(isComplete(xmlHttp)) {
				setTimeout(xmlHttp.responseText, 1);
			}
		});
	} else {

		url = url + "?" + pageData;
		dynamItSendRequest(url, function () {
			if(isComplete(xmlHttp)) {
				setTimeout(xmlHttp.responseText, 1);
			}
		});
	}

	return false;
}

/**************************************
* This method will turn an ordinary form into
* query string data.
**************************************/
function dynamItFormData(f) {
	var e;
	var data = new Array;
	for (var j = 0; j < f.elements.length; j++) {
		e = f.elements[j];
		if (e.name && e.name.length) {
			if((e.type != 'checkbox' && e.type != 'radio') || e.checked) {
				data.push(e.name + "=" + urlencode(e.value));
			}
	        }
	}
	return data.join("&");
}

/**************************************
* This method acts much like the dynamItPublish
* function but will visit a URL rather than
* publish a form. Data sent using GET
**************************************/
function dynamItSend(url) {
	dynamItSendRequest(url, function () {
		if(isComplete(xmlHttp)) {
			setTimeout(xmlHttp.responseText, 1);
		}
	});
}

function dynamItSendOnConfirm(url, message) {
	dynamIt__OnConfirm("dynamItSend('" + url + "');", message);
}

function dynamItLinkOnConfirm(url, message) {
	dynamIt__OnConfirm("location.href = '" + url + "';", message);
}

function dynamIt__OnConfirm(action, message) {

	var html = '';
	html += dialogTop('&nbsp;');
	html += '<div style="background-color:white;">';
	html += '	<div style="padding: 12px 12px 0 12px;">' + message + '</div>';
         html += '	<div style="text-align:center; padding: 12px;">';
	html += ' 		<input type="button" value=" &nbsp; Ok &nbsp; " onclick="' + action + '" id="confOkButton" />';
	html += '		<input type="button" value="Cancel" onclick="dynamItCloseDialog();" /></div>';
	html += '</div>';
	html += dialogBottom();

//	$("#dynamItPopUp").html(html);
//	dynamItResizeDialog(300, $("#dynamItPopUp").height());

	dynamItOpenDialog(html, 400, 'auto');
	$("#confOkButton").focus();
}

function dynamItPublishOnVerify(f) {

	if(dynamItVerify(f)) {
		return dynamItPublish(f);
	} else {
		return false;
	}

}


/**************************************
* dynamIt Form Verification
* Verify the form check for one of the following
* input from user on a given field:
*	none - no verification required
*	nonempty - verify field is not empty
*	zip - check for 5 or 9 digit zip code
*	phone - check for valid 7 or 10 digit phone number
*	email - check for a valid e-mail address
*	minlength - check for a given minimum length
*	matches - check that the value macthed that
*		of another specified field
*
**************************************/
function dynamItVerify(f) {
	var v, e;
	var returnValue = true;

	$("div.error").remove();

	for (var j = 0; j < f.elements.length; j++) {
		e = f.elements[j];
		v = $(e).attr("verify");
		if(v && v.length && v != "none") {
			if(!isValid(v, $(e).val())) {

				var emsg = $(e).attr("error");
				$('<div class="error">' + emsg + '</div>').insertAfter(e).show('slow');
				$(e).focus(function() {
					$(this).siblings("div.error").hide('slow', function() { $(this).remove(); } );
				});

				returnValue = false;
			}
		}
	}

	return returnValue;
}

function isValid(type, value) {
	if(type == "nonempty") {
		return value.length;
	} else if(type == "zip") {
		var zipRegex = /[0-9]{5}(-[0-9]{4})?/
		return value.match(zipRegex);
	} else if(type == "phone") {
		var phoneRegex = /([0-9]{3}-)?[0-9]{3}-[0-9]{4}/
		return value.match(phoneRegex);
	} else if(type == "email") {
		var emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/
		return value.match(emailRegex);
	} else if(type.indexOf("minlength") != -1) {
		var d = type.split('|');
		var min = parseInt(d[1], 10);
	  	return (value.length >= min);
	} else if(type.indexOf("matches") != -1) {
		var d = type.split('|');
		var field = d[1];
		var fieldval = $("#" + field).val();
		return (value == fieldval);
	}

	return true;
}



/**************************************
* Populate a <select> with the contents of a
* javascript object (key:value)
**************************************/
function dynamItPopulateSelect(sel, obj) {
	sel = dynamItElem(sel);

	var j;
	for ( j = sel.options.length-1; j >= 0; j-- ) {
		sel.options[j] = null;
	}

	j = 0;
	for( var i in obj ) {
		sel.options[j] = new Option( obj[i], i );
		j++;
	}
}

/**************************************
* PHP functions you know and love implemeneted
* in JavaScript.
**************************************/
function str_replace(find, replace, search) {
	return search.split(find).join(replace);
}

function urlencode(str) {
	return encodeURIComponent(str);
}

function substr(string, start, length) {
	l = parseInt(length);
	if(isNaN(l)) {
		return string.substring(start);
	} else {
		return string.substring(start, start + length);
	}
}

function stripslashes(str) {
	str = str_replace('\\\\', '\\', str);
	str = str_replace('\\\'', '\'', str);
	str = str_replace('\\\"', '\"', str);
	return str;
}

function in_array(needle, haystack) {
	for(var j = 0; j < haystack.length; j++) {
		if(needle == haystack[j])
			return true;
	}
	return false;
}

function trim(str) {
	return jQuery.trim(str);
}


function empty(o) {
	if ((null==o) || (undefined==o)) {
		return true;
	} else if (typeof(o)=='string') {
		return trim(o).length<=0;
	}
	return false;
}

function safeBoolean(b) {
	return empty(b)?false:b;
}