function isDefined(variable){
	return (typeof(window[variable]) == 'undefined')? false : true;
};

var _loaded_scripts = [];
$(document).ready(function(){
	$('script').each(function(){
		if (!this.src || this.src == '') return;
		var pos = $.inArray(this.src, _loaded_scripts);
		if (pos != -1) {
			_loaded_scripts.push(this.src);
		}
	});
});

$.ajaxSetup({
//	timeout: 3000,
//	type: 'POST',
	cache: true,
	beforeSend: function(){
		if (this.dataType == 'script') {
			var pos = $.inArray(this.url, _loaded_scripts);
			if (pos != -1) {
				return false;	
			}
			
			_loaded_scripts.push(this.url);
		}
		startWait();
	},
	complete: endWait
//	success: endWait //for using .load() or $.get()
//	, error: function(xhr, status, error) {
///*
//		var str = '';
//		for(var i in xhr) {
//			str += '\n' + i + ' : ' + xhr[i];
//		}
//		alert([xhr, status, error] + '\n' + str);
//*/
//	}
});

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

function ajax(url, method, params, before, success, error) {
	var 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(){
	$(":submit").attr("disabled", true);
	notifier.display('Loading...');
};

function endWait(){
	$(":submit").attr("disabled", false);
	notifier.hide();
};

function informer (msg){
   	$.jGrowl(msg, {
	    animateOpen: {
	        height: 'show'
	    }
	});
}

function win_popup(url, width, height){
	if (!width) width = 450;
	if (!height) height = 550;

	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="+width+",height="+height+"");
	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){
			success(msg);
			popup(msg, width, height);
	})
};

function popup(text, width, height){
	if (width == undefined) {
		width = 600;
	}

	if ($("div.popup").length > 0) {
		popupclean();
	}
	else {
		hideUnderPopup();
	}
	
//	$.jGrowl(text, { sticky: true, position: center });

	$("body").append("<script type='text/javascript'>$(function(){$(document).pngFix();})</script><div style='width:"+width+"' id='popup'  class=\"popup popup_block\">" +
	"<div class=\"popup_close\" onclick='popupclose();'><img alt=\"Close Window\" src='"+templatesRoot+"img/spacer.gif' width='30' height='30' /></div>"+
	"<div id='popupcontent'>"+text+"</div></div>");

	center("div#popup");
	applyCurtain();
	popupOpened = true;
};

function stopSubmitEvents() {
	try {
		window.stop();
		for(var i = 0 ; i < window.frames.length; i++) {
			window.frames[i].stop();
		}
	}
	catch(e) {
		window.document.execCommand('Stop');
		for(var i = 0 ; i < window.frames.length; i++) {
			var iFrameObject = window.frames[i];
			if (iFrameObject.contentWindow && iFrameObject.contentWindow.document) {
				iFrameObject = iFrameObject.contentWindow.document;
			}
			else if (iFrameObject.contentDocument) {
				iFrameObject = iFrameObject.contentDocument;
			}
			else if (iFrameObject.document) {
				iFrameObject = iFrameObject.document;
			}
			else {
				continue;
			}
			iFrameObject.execCommand('Stop');
		}
	}
	endWait();
}
function popupclose() {
	if (!popupOpened) return;
	stopSubmitEvents();

	popupclean();
	removeCurtain();
	popupOpened = false;
	
	showUnderPopup();
};


function hideUnderPopup(body) {
	if (!$.browser.msie || !($.browser.version < 7.0)) {
		return;
	}
	
	if (!body) body = $("body");
	$("object:visible", body).css("visibility", "hidden");
	$("select:visible", body).css("visibility", "hidden");
}

function showUnderPopup(body) {
	if (!$.browser.msie || !($.browser.version < 7.0)) {
		return;
	}
	
	if (!body) body = $("body");
	$("object:hidden", body).css("visibility", "visible");
	$("select:hidden", body).css("visibility", "visible");
}


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 + (988 - w) / 2;
	} else {
		x = (wsize[0]-w)/2 + wscroll[0];
	}
	y = (wsize[1]-h)/2 + 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(){
	var wsize = getWindowSize();
	$('body').append('<iframe src="'+templatesRoot+'black.html" style="width:'+wsize[0]+'px;height:'+wsize[1]+'px;  filter:alpha(opacity=0.0);-moz-opacity:.0;opacity:.0;background-color:#000000;" id="popupcurtain1" frameborder="none" scrolling="No" marginheight="0" marginwidth="0"></iframe>');
	$('#popupcurtain1').css("position:absolute")
	if ($.browser.msie && $.browser.version == 6){//for jquery < 1.3
		var dh = $(document).height();
        $('#popupcurtain1').css("position" , "absolute").height(dh);// do ie6 fix
		$('#popupcurtain1 >body').css("background", "black");
	} 
	$('#popupcurtain1').fadeTo(0.0, 0.5, function(){$("div.popup").show()});
};

function popupclean(){
	$('object', $("div.popup")).remove();
	$('embed', $("div.popup")).remove();
	$("div.popup").remove();
};
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 (typeof 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(); 
		}
	);
};


function setSwitchCollapseExpand(control_el_id, collapse_el_id, expand_el_id, state_el_id) {
	var control_el = $('#'+control_el_id);
	var collapse_el = $('#'+collapse_el_id);
	var expand_el = $('#'+expand_el_id);
	//--
	if (!$(control_el) || !$(collapse_el) || !$(expand_el))
		return;
	//--
	if ($(control_el).filter(':hidden').length) {
		$(control_el).show();
		$(collapse_el).show();
		$(expand_el).hide();
		$('#'+state_el_id).val(1);
	}
	else {
		$(control_el).hide();
		$(collapse_el).hide();
		$(expand_el).show();
		$('#'+state_el_id).val(0);
	};
}

function setSwitchCollapseExpandAdv(control_el_id, collapse_el_id, expand_el_id, parentObj) {
	if (typeof control_el_id == 'object') 
		var control_el = control_el_id;
	else if ($(parentObj))
		var control_el = $('#'+control_el_id, $(parentObj));
	else
		var control_el = $('#'+control_el_id);
		
	if (typeof collapse_el_id == 'object') 
		var collapse_el = collapse_el_id;
	else if ($(parentObj))
		var collapse_el = $('#'+collapse_el_id, $(parentObj));
	else 
		var collapse_el = $('#'+collapse_el_id);
		
	if (typeof expand_el_id == 'object') 
		var expand_el = expand_el_id;
	else if ($(parentObj))
		var expand_el = $('#'+expand_el_id, $(parentObj));
	else
		var expand_el = $('#'+expand_el_id);
	//--
	if (!$(control_el) || !$(collapse_el) || !$(expand_el))
		return;
	//--
	if ($(control_el).filter(':hidden').length) {
		var state_val = 1;
		$(control_el).show();
		$(collapse_el).show();
		$(expand_el).hide();
	}
	else {
		var state_val = 0;
		$(control_el).hide();
		$(collapse_el).hide();
		$(expand_el).show();
	};
	//--
	if (setSwitchCollapseExpandAdv.arguments.length > 4) {
		var state_el_id = setSwitchCollapseExpandAdv.arguments[4];
		if (typeof state_el_id == 'object') 
			var state_el = state_el_id;
		else if ($(parentObj))
			var state_el = $('#'+state_el_id, $(parentObj));
		else 
			var state_el = $('#'+state_el_id);
		$(state_el).val(state_val);
	}
}

/* add another record checkbox - using in popup window
	use in code:
		...
		    index_modal_success: function(msg){
		        if (!popupOpened) {
		        	popup(msg, '500', '500');
		        	addNewRecord = new objAddAnotherRecord(this.url);
		        }
		...
		    preset_modal_forms: function(){
		        endWait();
		        addNewRecord.updateStatus();
		        $('form', '#popupcontent').ajaxForm({
		        	beforeSubmit: addNewRecord.setStatus,
		            success: appliancegroups.index_modal_success            
		        });    
	
*/
var addNewRecord;
var objAddAnotherRecord = function(url) {
	var status = false;
	this.originalURL = url || null;
			
	this.getStatus = function() {
		return status ? true : false;
	};
	this.setStatus = function() {
		if ($('#add_another_record', '#popupcontent').filter(':checked').length) {
			status = true;
		}
		else {
			status = false;
		}
	};
	this.updateStatus = function() {
		$('#add_another_record', '#popupcontent').attr('checked', this.getStatus());
	};
};


function simple_tooltip(target_items, name){
	var toolTips = $('<div></div>');
	$("body").append(toolTips);
	
	$(target_items).each(function(i){		
		if (typeof $(this).attr('title') == "undefined") return;		
		var my_tooltip = $("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
 		$(toolTips).append(my_tooltip);
		$(this).removeAttr("title").mouseover(function(){
			my_tooltip.css({opacity:0.8, display:"none"}).fadeIn(400);
		}).mousemove(function(kmouse){
			var params = {};
			var offsetLeft	= kmouse.pageX+15;
			var offsetTop	= kmouse.pageY+15;
			var widthBlock	= my_tooltip.width();
			var wd = Math.max($('#page-all').width(), $(toolTips).width());
			if (wd < offsetLeft + widthBlock) {
				var offsetLeft1 = offsetLeft - Math.ceil(widthBlock / 2 + 10);
				var offsetLeft2 = Math.max(wd - widthBlock - 10, 10);
				offsetLeft = Math.min(offsetLeft1, offsetLeft2);
				offsetTop += 7;
			}
			params.left		= offsetLeft;
			params.top		= offsetTop;
			params.width	= widthBlock;
			my_tooltip.css(params);				
//			my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
		}).mouseout(function(){
			my_tooltip.fadeOut(400);
		});
	});
}

function popup_preview(url, ratio) {
	var width = 640;
	var height = 480;
	if (ratio == null) {
	ratio = 4 / 3;
	};
	if (ratio > 1) {
	height = Math.round(width / ratio);
	}
	else {
	width = Math.round(height * ratio);
	};
	var top = Math.round((screen.height - height) / 2);
	var left = Math.round((screen.width - width) / 2);
	window.open(url, '', 'location=0,status=0,resizable=0,menubar=0,scrollbars=0,width='+width+',height='+height+',top='+top+',left='+left);
}

function show_selected(list_id){
	return show_selected_block($("tr[id='"+list_id+"']"), '#8DAED8');
//	$("tr[id='"+list_id+"']").effect("highlight", {color: "#8DAED8"}, 3000);
}

function show_selected_text(list_id){
	var prev_color = $('a#'+list_id).css('color');
	$('a#'+list_id).animate({color: "#8DAED8"}, 500);
	$('a#'+list_id).animate({color: "#8DAED8"}, 1000);
	$('a#'+list_id).animate({color: prev_color}, 500);
}

function show_selected_block(list_id, highlight_color){
	if (typeof list_id == 'object') {
		var elm = $(list_id);
	}
	else if (typeof list_id == 'string') {
		var elm = $("[id='"+list_id+"']");
	}
	else {
		return;
	}
	if (!highlight_color) {
		highlight_color = '#8DAED8';
	}
	elm.effect("highlight", {color: highlight_color}, 3000);
}

function window_popup(popW, popH, link) {
    var w = screen.width;
    var h = screen.height;
    var leftPos = (w-popW)/2;
    var topPos = (h-popH)/2;
    window.open(link, '', 'top=' + topPos + ',left=' + leftPos + ',width=' + popW + ',height=' + popH + ',scrollbars=yes');
}

function first_focus(forms) {
	if (forms == undefined) return;
		
	if (forms[0].length == 1) {
		_forms = [forms];
	} else {
		_forms = forms;
	}
	
	for (j=0; j<_forms.length; j++) {
		var aForm = document.getElementById(_forms[j]);

		if (aForm!=null && aForm.elements[0]!=null) {
			var i;
			var max = aForm.length;
			for( i = 0; i < max; i++ ) {
				//console.log(aForm.elements[ i ].type, aForm.elements[ i ].disabled, aForm.elements[ i ].readOnly, aForm.elements[ i ].name);
				if( aForm.elements[ i ].type == "text" &&
				!aForm.elements[ i ].disabled &&
				!aForm.elements[ i ].readOnly ) {
					aForm.elements[ i ].focus();
					break;
				}
			}
		}
	}
}


