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       :    "%d/%m/%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\">"+	
	"<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>"+				
	"<div id='popupcontent'>"+text+"</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="'+templatesRoot+'black.html" style="position:absolute;top:0px;left:0px;width:'+wsize[0]+'px;height:'+wsize[1]+'px;  filter:alpha(opacity=0);-moz-opacity:.0;opacity:.0;" id="popupcurtain1" frameborder="none" scrolling="No" marginheight="0" marginwidth="0"></iframe>');
	$('#popupcurtain1').fadeTo(0, 0.0, function(){$("div.popup").show()});
};

function popupclean(){
	$("div.popup").remove();
};

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