/****************************************************************************
*
* 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
*
****************************************************************************/

var DEFAULT_WIDTH = 0;
var DEFAULT_HEIGHT = 0;
var DIALOG_TOP = '';
var DIALOG_BOTTOM = '';

var IE7 = false;
var IE6 = false;
var FF = false;
var UA = '';

var dialogOpen = false;
var dialogScroll = 0;

/**
* Initiate the dynamItScript
*   options - JS object definin various dialog options
* 	xout - JS object for standard close button placement
*	coverColor - hex code for the color to which we will fade the bg (default: #000000)
*	dialogTop - default HTML header to load into the dialog on automated messages
*	dialogBottom - default HTML footer to load into the dialog on automated messages
*	dialogWidth - default width of dialog
*	dialogHeight - default height of dialog
**/
function dynamItScript(o) {

	/** initiate dynamItScript options **/
	if( !o ) 		o = {};
	if( !o.xout )		o.xout = {};
	if( !o.xout.image ) 	o.xout.image = 'img/admin/ajax-x.png';
	if( !o.xout.width ) 	o.xout.width = 23;
	if( !o.xout.height ) 	o.xout.height = 23;
	if( !o.xout.right ) 	o.xout.right = 15;
	if( !o.xout.top ) 	o.xout.top = 10;

	if( !o.coverColor ) 	o.coverColor = '#000000';

	if( !o.dialogTop ) 	o.dialogTop = '<div class="ajax"><div class="ajax-title"><h1>%s</h1></div><div class="ajax-body"><div class="ajax-padd">';
	if( !o.dialogBottom ) 	o.dialogBottom = '</div></div><div class="ajax-foot"></div></div>';
	if( !o.dialogWidth ) 	o.dialogWidth = 500;
	if( !o.dialogHeight ) 	o.dialogHeight = 200;


	DEFAULT_WIDTH = o.dialogWidth;
	DEFAULT_HEIGHT = o.dialogHeight;
	DIALOG_TOP = o.dialogTop;
	DIALOG_BOTTOM = o.dialogBottom;

	/** Setup Browser and User Agent **/
	UA = navigator.userAgent;
	if (window.XMLHttpRequest) {
		if(document.epando){
			//IE7
			IE7 = true;
		}else{
			//mozilla, safari, opera, etc
			FF = true;
		}
	} else {
		// IE6, older browsers
	         IE6 = true;
	}


	/** Initiate dialog windows **/
	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: o.coverColor,
		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: "1px",
		height: "1px",
		display: "none",
		border: "0",
		zIndex: "1000002"});

	$("<div></div>").prependTo("#dynamItPopUpWin").attr("id", "dynamItPopUpX").css({
		position: "absolute",
		width: o.xout.width + "px",
		height: o.xout.height + "px",
		top: o.xout.top + "px",
		right: o.xout.right + "px",
		backgroundImage: "url(" + o.xout.image + ")",
		cursor: "pointer"
	}).click(function() {
		dynamItCloseDialog();
	});

	$("<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"
	});


	/** setup the mouse motion detection **/
	document.onmousemove = dynamItSetMouse;


	/** FIX IE 6 nonsense **/
	$(window).scroll(function() {

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

	}).resize(function() {

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


	/** attach default focus and blur events to replace values **/
	$('input, textarea').focus( function() {
		if( $(this).val() == $(this).attr('title') ) {
			$(this).val('');
		}
	}).blur( function() {
		if( $(this).val() == '' ) {
			$(this).val( $(this).attr('title') );
		}
	});

}


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 will define markup for our default dialog
* box used in dynamIt__OnConfirm() and dynamItConfDialog()
**************************************/
function dialogTop(title) {
	if( !title ) title = '';
	return sprintf( DIALOG_TOP, title );
}

function dialogBottom() {
	return DIALOG_BOTTOM;
}

/**************************************
* This method and variables will allow for
* the capturing of the mouse position at any time
**************************************/

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;
        ymouse = e.clientY;

        if (document.body) {
            xmouse += document.body.scrollLeft;
            ymouse += document.body.scrollTop;
        }
        if (document.documentElement) {
            xmouse += document.documentElement.scrollLeft;
            ymouse += 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') ? DEFAULT_HEIGHT : (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') ? DEFAULT_HEIGHT : (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) {

	var loading = 'Processing...';
	if(!message) message = loading;

	var html = '';
	html = dialogTop('&nbsp;');
	html += '<div style="padding: 30px; text-align:center;">';
	html += '	<img src="/img/ajax-loader.gif" alt="' + loading + '" /><br />';
	html += message;
	html += '</div>';
	html += dialogBottom();

	dynamItOpenDialog(html, DEFAULT_WIDTH, DEFAULT_HEIGHT);

}

function dynamItConfDialog(message, cancel) {

	var html = '';
	html = dialogTop('&nbsp;');
	html += '	<div>' + 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, DEFAULT_WIDTH, $("#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)) {
// Patch for Windows ajax load errors
if (url.substring(0,19) == 'forms/frm_eclub.php' && xmlHttp.responseText.length < 1) {
	var eclubvars = url.substring(32);
	window.location = 'http://www.charleys.com/e-club/?'+eclubvars;
}
			if(container) {
				closeSimpleLoading();
				$(container).html(xmlHttp.responseText);
			} else {
				dynamItOpenDialog(xmlHttp.responseText, w, h);
			}
			if(callback) { callback(xmlHttp.responseText); }
		}
	});

}

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 given a url will use AJAX to retrieve
* the output at that URL and send that response data to
* specified callback function. This data will also be
* stored by specified key in a global variable for later use.
**************************************/
var dynamItLoadDataResp = {};
function dynamItLoadData(url, key, callback) {

	dynamItSendRequest(url, function() {
		if(isComplete(xmlHttp)) {

			if(key && key.length) {
				dynamItLoadDataResp[key] = xmlHttp.responseText;
			}

			if(callback) {
				callback(xmlHttp.responseText);
			}

		}
	});

}

/**************************************
* 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, callback) {
	var url = f.action;
	var pageData = dynamItFormData(f);

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

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

	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));
			}
	        }


		if(e.type == 'submit') {
			$(e).attr('title', e.value);
			e.value = 'Processing...';
			e.disabled = true;
		}
	}
	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, DEFAULT_WIDTH, '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)) {
				var emsg = $(e).attr("error");
				$(e).parent().append('<div class="error">' + emsg + '</div>').show('slow');
				$(e).focus(function() {
					$(this).siblings("div.error").hide('slow', function() { $(this).remove(); } );
				});

				returnValue = false;
			}
		}
	}

	return returnValue;
}

function isValid(type, e) {
	var value = $(e).val();
	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);
	} else if (type == "checked") {
	       return e.checked;
	} else if(type.indexOf("if") != -1) {
		var d = type.split('|');
		var field = d[1];
		var fieldval = $("#" + field).val();
		var checkval = d[2];
		return (fieldval != checkval || value.length);
	}

	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;
}

/**
only supports %s, %d, %f, and %%
args must be an array
**/
function sprintf(format, args) {
	var split = format.split('%');
	var print = split[0];
	var offset = 0;
	var index, val, flag;
	for(var i = 1; i < split.length; i++) {
		flag = split[i].substring(0, 1);
		index = i - offset - 1;
		switch( flag ) {
			case '%': val = '%'; offset++; break;
			case 'f': val = parseFloat(args[index]); break;
			case 'd': val = parseInt(args[index]); break;
			case 's': default: val = '' + args[index]; break;
		}

		print += val + split[i].substring(1);
	}
	return print;
}