function isDefined(variable){
	return (typeof(window[variable]) == 'undefined')? false : true;
};

function ArrayInsert(arr, index, v){
	if (index >= 0) {
		len = arr.length;
		for (i=len-1;i>index;i--) {
			if (arr[i+1] == undefined) {
				arr[i+1] = new Array;
			}
			arr[i+1] = arr[i];
		}
		
		arr.splice(parseInt(index)+1, 1, v);
		return arr;
	}
	return -1;
};



function ArrayIndexOf(arr, v){
	for (i in arr) {
		if (arr[i] == v) {
			return parseInt(i);
		}
	}
	return -1;
};

//Array.prototype.insert = function( i, v ) {
//	if( i>=0 ) {
//		var a = this.slice(), b = a.splice( i );
//		a[i] = v;
//		return a.concat( b );
//	}
//}
//
//Array.prototype.indexOf = function( v, b, s ) {
// for( var i = +b || 0, l = this.length; i < l; i++ ) {
//  if( this[i]===v || s && this[i]==v ) { return i; }
// }
// return -1;
//};

function ajax(url, method, params, before, success, error) {
	options = {
		url:url,
		method:method
	};
	if (params != undefined && params != '') options['data'] = params;
	if (before != undefined && before != '') options['beforeSend'] = before;
	if (success != undefined && success != '') options['success'] = success;
	if (error != undefined && error != '') options['error'] = error;
	$.ajax(options);
};

function setupCalendar(input_id, btn_id) {
	Zapatec.Calendar.setup({
		inputField     :    input_id,
		ifFormat       :    "%m/%d/%Y",
		showsTime      :     false,
		button         :    btn_id,
		align          :    "B2"
	});
};

function startWait(msg){	
	if (msg == undefined) msg = 'Loading...';		
	notifier.display(msg);	
};

function endWait(){
	notifier.hide();
};

function win_popup(url){
	if (!window.popupNum) window.popupNum = 0;
	window.popupNum++;
	mywindow = window.open (url, window.name + "_popup" + window.popupNum, "menubar=1,resizable=1,location=1,status=1,scrollbars=1, width=450,height=550");
	mywindow.moveTo(100,100);
};

var popupOpened = false;
var response;

function ajaxpopup(url, width, height, before, success){
	if (!isDefined('before')) {
		before=function(){startWait()};
	}
	if (success == undefined) {		
		success=function(msg){endWait()};
	}
	ajax(url, 'GET', '', before, function(msg){
			var div = document.createElement('div');
			div.innerHTML = msg;
			imgs = div.getElementsByTagName('img');
			var hooked = false;
			for (i=0; i<imgs.length; i++){
				if (!hooked && !imgs[i].complete){
					imgs[i].onload = function(){ popup(msg, width, height); success(msg) };
					hooked = true;
				}
			}
			if (!hooked){
				popup(msg, width, height);
				success(msg);
			}
			div = null;
	})
};

function popup(text, width, height){

	if (width == undefined) {
		width = 600;
	}
	if ($("div.popup").length > 0) {
		popupclean();
	}
	$("body").append("<script type='text/javascript'>$(function(){$(document).pngFix();})</script>"+
	"<div style='width:"+width+"' id='popup'  class=\"popup\">"+
	"<table cellpadding='0' cellspacing='0' border='0' width='100%'>"+
	"<tr>"+
		"<td colspan='3'>"+
			"<table width='100%' border='0' cellpadding='0' cellspacing='0'><tr>"+
				"<td class='top-left-corner'><img src='"+templatesRoot+"img/spacer.gif' width='34' height='10' alt='' /></td>"+
				"<td class='top-bg' width='100%'><img src='"+templatesRoot+"img/spacer.gif' width='100%' height='10'  alt='' /></td>"+
				"<td class='top-right-corner'><img src='"+templatesRoot+"img/spacer.gif' width='34' height='10' alt='' /></td>"+
		"</tr></table>"+	
		"</td>"+
	"</tr>"+
	"<tr valign='top'>"+
		"<td class='left-cols'>"+
			"<table cellpadding='0' cellspacing='0'>"+
				"<tr><td class='col-top left1'><img src='"+templatesRoot+"img/spacer.gif' width='14' height='25' alt='' /></td></tr>"+
				"<tr><td class='left-shadow'><img src='"+templatesRoot+"img/spacer.gif' alt='' /></td></tr>"+
				"<tr><td class='col-bot left2'><img src='"+templatesRoot+"img/spacer.gif' width='14' height='21' alt='' /></td></tr>"+
			"</table>"+
		"</td>"+
		"<td class='popup_inner'>"+
			"<table cellpadding='0' cellspacing='0' width='100%'>"+				
				"<tr><td><div class='popup_close' align='right'><a href='javascript://' onclick='popupclose(); return false;' title='Close Popup Window'>"+
					"<img src='"+templatesRoot+"img/icons/close.gif' alt='Close Popup Window' class='vm mr4 mt4'  /></a></div>"+
				"</td></tr>"+
				"<tr><td id='popupcontent'>"+text+"</td></tr>"+
			"</table>"+
		"</td>"+
		"<td class='right-cols'>"+
			"<table cellpadding='0' cellspacing='0'>"+
				"<tr><td class='col-top right1'><img src='"+templatesRoot+"img/spacer.gif' width='24' height='25' alt='' /></td></tr>"+
				"<tr><td class='right-shadow'><img src='"+templatesRoot+"img/spacer.gif'  alt='' /></td></tr>"+
				"<tr><td class='col-bot right2'><img src='"+templatesRoot+"img/spacer.gif' width='24' height='21' alt='' /></td></tr>"+
			"</table>"+
		"</td>"+
	"</tr>"+
	"<tr><td colspan='3'>"+
		"<table width='100%' border='0' cellpadding='0' cellspacing='0'><tr>"+
				"<td class='bottom-left-corner'><img src='"+templatesRoot+"img/spacer.gif' width='50' height='24' alt='' /></td>"+
				"<td class='bottom-bg' width='100%'><img src='"+templatesRoot+"img/spacer.gif' width='100%' height='24'  alt='' /></td>"+
				"<td class='bottom-right-corner'><img src='"+templatesRoot+"img/spacer.gif' width='50' height='24' alt='' /></td>"+
		"</tr></table>"+	
	"</td>"+
	"</table></div>");
	center("div.popup");
	applyCurtain();
	popupOpened = true;
};


function popupclose() {
	popupclean();
	removeCurtain();
	popupOpened = false;
};


function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
};

function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth, myHeight ];
};

function getCenteredArea(el){
	w = $(el).width();
	h = $(el).height();
	wsize = getWindowSize();
	wscroll = getScrollXY();
	if ($("#page-all").width() != null) {
		x = ( wsize[0] - $("#page-all").width() ) /2 + (850 - w) / 2;
		//x = ( wsize[0] - $("#page-all").width() ) /2 - 96;
	} else {
		x = (wsize[0]-w)/2 + wscroll[0];
	}
	y = (wsize[1] > h ? ( wsize[1] - h ) / 2 : 10) + wscroll[1];
	return [x, y, x+w, y+h];
};

function center(el){
	area = getCenteredArea(el);
	$(el).css("left", area[0]);
	$(el).css("top", area[1]);
	
};

function removeCurtain(){
	$("#popupcurtain1").remove();
};

function ShowBlock(data, width, height){
	//statusControl(0);
	popup(data, width, height);
};

function applyCurtain(){	
	wsize = getWindowSize();
	$('body').append('<iframe src="../templates/prototype/black.html" style="background:black; width:'+wsize[0]+'px;height:'+wsize[1]+'px;  filter:alpha(opacity=0.0);-moz-opacity:.0;opacity:.0;background-color:#000000;" id="popupcurtain" frameborder="none" scrolling="No" marginheight="0" marginwidth="0"></iframe>');
	$('#popupcurtain').css("position:absolute");
	if ($.browser.msie && $.browser.version == 6){//for jquery < 1.3
		dh = $(document).height();
        $('#popupcurtain').height(dh);// do ie6 fix
		$('#popupcurtain >body').css("background", "black");
	}
	$('#popupcurtain').css('display', 'block');	
	$('#popupcurtain').fadeTo(0.05, 0.5, function(){$("div.popup").show()});	
}

function popupclean(){
	$('#popupcurtain').css('display', 'none'); 	
	$("div.popup").remove();
};
//
//function GetAjaxContent(popup, url, additional, callback, method) {
//	if (method = 'undefined'){method = 'POST';}
//	if (document.getElementById) {
//		var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
//	}
//	if (x) {
//		x.onreadystatechange = function() {
//		    if (x.readyState == 4 && x.status == 200) {
//		        if (popup === true) {
//		        	ShowBlock( x.responseText, 600, 500);
//		        } else {
//		        	if (popup != '') {
//		        		$("#"+popup).html(x.responseText);
//		        	} else {
//		        		eval("response = ("+x.responseText+")");
//		        	}
//		        }
//		        if (callback) {
//					try	{
//						eval(callback+"()");
//					} catch(e) {}
//		        }
//		    }
//		}
//	}
//	x.open(method, url+'&'+additional,true);
//	x.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//	if (method == 'GET') {
//		x.send(null);
//	} else {
//		x.send(url+'&'+additional);
//	}
//	
//}

function escapeURI(value){
	return escape(encodeURI(value));
};

// empty popup - set response array
// popup id of element - set responde html in this element
// popup true - popap

function getFormFields(formName, popup, url, callback, method) {
	if (method = 'undefined'){method = 'POST';}
	str = '';
	for(i=0; i<document.getElementById(formName).elements.length; i++) {
		str += '&'+document.getElementById(formName).elements[i].name+'='+escapeURI(document.getElementById(formName).elements[i].value);
	}
	GetAjaxContent(popup, url, str, callback, method);
	return false;
};

function rolloverEnhancedCopy(container_class, clipped_class, enhanced_class, clip_width, clip_height) {
	
	$("."+clipped_class).css({
		position: 'absolute',
		width: clip_width,
		height:(clip_height + 2),
		clip: 'rect(0px '+clip_width+'px '+clip_height+'px 0px)'
	});
	$("."+container_class).hover(
		function () {
			$(this).children("."+enhanced_class).show();  
			$(this).children("."+clipped_class).hide();  
		}, 
		function () {
			$(this).children("."+enhanced_class).hide();
			$(this).children("."+clipped_class).show(); 
		}
	);
};

/* FC integration function for submit data and parse XML response */
function submit_fc_form(form_title, form_id, fc_form_url){
	if (notifier) notifier.display("Please wait...");
	
	var formData = $('#' + form_id).serialize();
	formData = "fcScriptPath=" + fc_form_url + "&" + formData; 

	var divId = form_id + "_div";

	$.ajax({
		type: "POST",
		dataType: "xml",
		url: '?controller=firstcontactadaptor&action=fcsubmit', 
		data: formData,
		async: "true",
		success: function(xml) {
			if (notifier) notifier.hide();
			var blankFieldsPresent = emailInvalid = error = false;
			var responseTxt = "";
			$(xml).find("returnedData > errors > error").each(function(){
				if ($(this).attr("type") == "blank") {
					blankFieldsPresent = true;
					error = true;
				}
				
				if ($(this).attr("type") == "validate") {
					emailInvalid = true;
					error = true;
				}

				if ($(this).attr("type") == "already_registered") {
					responseTxt += "You have already registered with us.\n\n";
					error = true;
				}

			});
			if (blankFieldsPresent) {
				responseTxt += "Please fill all required fields.\n\n";
			};
			if (emailInvalid) {
				responseTxt += "E-mail Address is invalid.\n\n";
			};
			
			if (!error) {
				$(xml).find("returnedData > message").each(function(){
					if ($(this).attr("type") == "thank") {
						responseTxt += "<br/><div align='Center'>Thank you for your interest.<br/>You will be hearing from us soon.</div>";
						document.getElementById(divId).innerHTML = responseTxt;
					} else {
						error = true;
					}
				});
				
				if (error) {
					responseTxt += "Unknown error, please try again later.\n\n";
				};
			};

			if (error) {
				alert(form_title + ":\n\n" + responseTxt);
			};
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			if (notifier) notifier.hide();
			alert(form_title + ": an error occured while connecting to the server, please try again later.\n\n");
		}
	});
};


function setup_fc_form(form_title, form_id){
	//if (notifier) notifier.display("Please wait...");
	
	//var formData = $('#' + form_id).serialize();
	//formData = "fcScriptPath=" + fc_form_url + "&" + formData; 

	var divId = form_id + "_div";

	var options = {
		type: "POST",
		dataType: "xml",
		url: '?controller=firstcontactadaptor&action=fcsubmit', 
		async: "true",
		beforeSubmit: function(){
			if (notifier) notifier.display("Please wait...");
		},		
		success: function(xml) {			
			if (notifier) notifier.hide();
			var blankFieldsPresent = emailInvalid = error = false;
			var responseTxt = "";
			$(xml).find("returnedData > errors > error").each(function(){
				if ($(this).attr("type") == "blank") {
					blankFieldsPresent = true;
					error = true;
				}
				
				if ($(this).attr("type") == "validate") {
					emailInvalid = true;
					error = true;
				}

				if ($(this).attr("type") == "already_registered") {
					responseTxt += "You have already registered with us.\n\n";
					error = true;
				}

			});
			if (blankFieldsPresent) {
				responseTxt += "Please fill all required fields.\n\n";
			};
			if (emailInvalid) {
				responseTxt += "E-mail Address is invalid.\n\n";
			};
			
			if (!error) {
				$(xml).find("returnedData > message").each(function(){
					if ($(this).attr("type") == "thank") {
						responseTxt += "<br/><div align='Center'>Thank you for your interest.<br/>You will be hearing from us soon.</div>";
						document.getElementById(divId).innerHTML = responseTxt;
					} else {
						error = true;
					}
				});
				
				if (error) {
					responseTxt += "Unknown error, please try again later.\n\n";
				};
			};

			if (error) {
				alert(form_title + ":\n\n" + responseTxt);
			};
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			if (notifier) notifier.hide();
			alert(form_title + ": an error occured while connecting to the server, please try again later.\n\n");
		}
	};
	$('#' + form_id).ajaxForm(options);
};

function informer (msg){
   	$.jGrowl(msg, {
	    animateOpen: {
	        height: 'show'
	    }
	});
}