//
// Alta v1.00 - Copyright (c) 2005 Altanet S.A.
// Global Functions
//
var Browser = new Object();
Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument!='undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox")!=-1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1);

if (window.Event)
{
	document.captureEvents(Event.KEYDOWN); 
	document.onkeydown = setkey;
}
else
{
	document.onkeydown = function()
	{
		return setkey(event);
	}
}

function setkey(event) 
{ 
	//evt.altKey, evt.ctrlKey, evt.shiftKey, evt.keyCode
	//alert(event.keyCode);
	
	if(event.ctrlKey && event.keyCode == 88 && GetObject("___DELETE___"))
	{
		GetObject("___DELETE___").click();
		return false;
	}
	else if(event.ctrlKey && event.keyCode == 88 && GetObject("_CUSTOM_DELETE_"))
	{
		GetObject("_CUSTOM_DELETE_").click();
		return false;
	}
	else if(event.keyCode == 27 && GetObject("___CANCEL___"))
	{
		GetObject("___CANCEL___").click();
		return false;
	}
	else if(event.ctrlKey && event.keyCode == 78 && GetObject("___NEWRECORD___"))
	{
		//GetObject("___NEWRECORD___").click();
		//return false;
	}
	else if(event.ctrlKey && event.keyCode == 69 && GetObject("___EDIT___"))
	{
		GetObject("___EDIT___").click();
		return false;
	}
	else if(event.ctrlKey && event.keyCode == 34 && GetObject("__NEXT_STEP__"))
	{
		GetObject("__NEXT_STEP__").click();
		return false;
	}
	else if(event.ctrlKey && event.keyCode == 33 && GetObject("__PREVIEWS_STEP__"))
	{
		GetObject("__PREVIEWS_STEP__").click();
		return false;
	}
	else if(event.ctrlKey && event.keyCode == 83 && GetObject("___SAVE___"))
	{		
		GetObject("___SAVE___").click();
		return false;
	}
	else if(event.shiftKey && event.keyCode == 191 && GetObject("___HELP___"))
	{		
		GetObject("___HELP___").click();
		return false;
	}
}	

function GetObject(id){
	if (document.getElementById)
		return document.getElementById(id);
	else if (document.all)
		return document.all[id];
	else
		return null;
}

var obj_event = null;
function mainProcessLinks(e) { 
	var targ;
	if (!e) var e = window.event;
	if (e.target){
		targ = e.target;
	} else if (e.srcElement){
		targ = e.srcElement;
	}
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

	if (targ.tagName == "INPUT"){
		obj_event = targ;
	}
	else{
		obj_event = null;
	}
	
	try
	{
		if(ControlWindow != null)
		{
			ControlWindow.focus();
		}
	}catch(e){}
}

document.onclick = mainProcessLinks;

var OverrideAltaValidation = false;

function AltaValidation()
{
	if(OverrideAltaValidation)
		return true;
		
	try
	{
		if (obj_event != null)
		{
			if (obj_event.type == "submit" && obj_event.onclick == null){
				return true;
			}
		}

		if(!CustomValidationValidate())
			return false;

		if(!MultilinqualValidationValidate())
			return false;

		if (obj_event != null)
		{
			
			if (obj_event.type == "submit" && obj_event.onclick != null){
				if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();
				if (typeof(ValidatorOnSubmit) == "function" && !ValidatorOnSubmit()) return false;
			}
		}
		
	}catch(e) {
		alert(e)
		return false;	
	}
	
	return true;
}

function CustomValidationValidate()
{
	if(typeof(CustomValidation) == "object")
	{
		for(var i=0;i<this.CustomValidation.length;i++){
			V_obj = GetObject(CustomValidation[i][0]);
			if(V_obj)
			{
				if (V_obj.value == "" && CustomValidation[i][2] == 1){
					MakeStar(V_obj);
					return false;
				}
				else if (V_obj.value != "" && Validator(V_obj.value,CustomValidation[i][1]) == null)	{
					MakeStar(V_obj);
					return false;
				}else{
					RemoveStar(V_obj);
				}
			}
		}
	}
	return true;
}

function MultilinqualValidationValidate()
{
	if(typeof(MultilinqualValidation) == "object")
	{
		for(var i=0;i<MultilinqualValidation.length;i++){
			var strMV = MultilinqualValidation[i] + "";
			if(!ValidateMultilinqual(strMV))
				return false;
		}
	}
	return true;
}

function eC(command,CauseValidation,ValidateSelection,ConfirmMessage)
{
	if (!CauseValidation)
		OverrideAltaValidation = true;
	
	if (ValidateSelection)
	{
		if (!ValidateCheck())
		{
			return;
		}
	}
	
	if(ConfirmMessage && ConfirmMessage!= '' && !window.confirm(ConfirmMessage))
		return;
	
	GetObject("ToolBarCommand").value = command;
	if (GetObject("ToolBarCommand").PostBackButton)
		GetObject(GetObject("ToolBarCommand").PostBackButton).click();
	else
		GetObject("t_sitemenu_PostBackBtn").click();
}



function ValidateCheck() {
	myOption = -1;
	cForm = document.forms[0];
	if (cForm.radio_sel)
	{
		if (cForm.radio_sel.length)
		{
			for (var i=0; i<cForm.radio_sel.length; i++) {
				if (cForm.radio_sel[i].checked) {
					myOption = i;
				}
			}
		}
		else if (cForm.radio_sel.checked) 
		{
			myOption = 1;
		}
	}
	if (myOption == -1) {
		if (typeof(RecordSelect) == 'function') 
		{
			RecordSelect();
		}
		else
		{
			alert("Please select a record.");
		}
		return false;
	}
	return true;
}

function Help(key,lang)
{
	var argument = PopupWindowArguments(600,400,screen.width - 610,"yes");
	var cWindow = window.open("AltaB2xCore/help/help.html?bridge=help&key=" + (key ? key : ""),'help',argument,true);
	cWindow.focus();
}


function lsetup(target)
{
	if (!target)
		target = this;
	
	var o_set = target.document.getElementById('loaderContainerWH');
	var o_getH = target.document.getElementsByTagName('BODY')[0];
	o_set.style.height = o_getH.scrollHeight;
}

function lon(target)
{
	if (!target)
		target = this;

	lsetup(target);
	target.document.getElementById("loaderContainer").style.display = "";
	
	return true;
}

function los(target)
{
	if (!target)
		target = this;
		
	target.document.getElementById("loaderContainer").style.display = "none";
	return true;
}

/*Upload Control*/

var CurrentFileObject;
function GetFile(obj,url)
{
	CurrentFileObject = GetObject(obj);
	var argument = PopupWindowArguments("600","600");
	var cWindow = window.open(url,'window',argument,true);
}

function SetUrl(filepath)
{
	CurrentFileObject.value = filepath;
	CurrentFileObject = null;
}

var CurrentReturnValObjectID;
function GetBridgePage(bridge,module,custom,ReturnValObjectID)
{
	CurrentReturnValObjectID = ReturnValObjectID;
	var argument = PopupWindowArguments(600,600);
	var cWindow = window.open("default.aspx?bridge=" + bridge + (custom ? "&c=true" : "") + (module ? "&m=" + module : ""),'window',argument,true);
	cWindow.focus();
}

function PopupWindowArguments(width,height,left,status)
{
	var argument = "channelmode=no,";
	argument += "directories=no,";
	argument += "fullscreen=no,";
	argument += "location=no,";
	argument += "menubar=no,";
	argument += "resizable=yes,";
	argument += "scrollbars=yes,";
	argument += "status=" + ( status ? status : "no") + ",";
	argument += "titlebar=no,";
	argument += "toolbar=no,";
	argument += "width=" + (width ? width : 500) + ",";
	argument += "height=" + (height ? height : 500) + ",";
	argument += "top=" + "0" + ",";
	argument += "left=" + (left ? left : (screen.width - (width ? (width+10) : 550))) + "";
	return argument;
}


function Validator(op, dataType) {
	function Properties(){
		this.decimalchar = ","; // For Greece
		this.groupchar = "."; // For Greece
		this.digits = "2";
		this.dateorder = "ymd";//dmy
		this.century = "2000";
		this.cutoffyear = "2029";
	}

	var val = new Properties();

	function GetFullYear(year) {
		return (year + parseInt(val.century)) - ((year < val.cutoffyear) ? 0 : 100);
	}
	var num, cleanInput, m, exp;
	if (dataType == "Integer") {
		exp = /^\s*[-\+]?\d+\s*$/;
		if (op.match(exp) == null) 
			return null;
		num = parseInt(op, 10);
		return (isNaN(num) ? null : num);
	}
	else if (dataType == "Double") {
		exp = new RegExp("^\\s*([-\\+])?(\\d+)?(\\" + val.decimalchar + "(\\d+))?\\s*$");
		m = op.match(exp);
		if (m == null)
			return null;
		cleanInput = m[1] + (m[2].length>0 ? m[2] : "0") + "." + m[4];
		num = parseFloat(cleanInput);
		return (isNaN(num) ? null : num);            
	} 
	else if (dataType == "Currency") {
		exp = new RegExp("^\\s*([-\\+])?(((\\d+)\\" + val.groupchar + ")*)(\\d+)"
						+ ((val.digits > 0) ? "(\\" + val.decimalchar + "(\\d{1," + val.digits + "}))?" : "")
						+ "\\s*$");
		m = op.match(exp);
		if (m == null)
			return null;
		var intermed = m[2] + m[5] ;
		cleanInput = m[1] + intermed.replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((val.digits > 0) ? "." + m[7] : 0);
		num = parseFloat(cleanInput);
		return (isNaN(num) ? null : num);            
	}
	else if (dataType == "Date") {
		var temp_op = op.replace(/_/g, "").replace(/\//g, "");
		if(temp_op != "")
		{
			var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\s*$");
			m = op.match(yearFirstExp);
			var day, month, year;
			if (m != null && (m[2].length == 4 || val.dateorder == "ymd")) {
				day = m[6];
				month = m[5];
				year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10))
			}
			else {
				if (val.dateorder == "ymd"){
					return null;		
				}						
				var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
				m = op.match(yearLastExp);
				if (m == null) {
					return null;
				}
				if (val.dateorder == "mdy") {
					day = m[3];
					month = m[1];
				}
				else {
					day = m[1];
					month = m[3];
				}
				year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10))
			}
			month -= 1;
			var date = new Date(year, month, day);
		    
			return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
		}
		else
		{
			return op.toString();
		}
	}
	else if (dataType == "DateTime") 
	{	
		var temp_op = op.replace(/_/g, "").replace(/\//g, "").replace(/:/g, "").replace(/ /g, "");;
		if(temp_op.length > 0)
		{
			if(temp_op.length == 14) return op.toString();
			else return null;
		}
		else
		{
			return op.toString();
		}
	}
	else {
		return op.toString();
	}
}

MakeStar = function(control){
	
	var _er = "";
	_er = "&nbsp;<span class='error' id='" + control.name + "sp' name='" + control.name + "sp'>*</span>";
	if (GetObject(control.id + 'sp')){
		GetObject(control.id + 'sp').style.visibility = 'visible';
		return;
	}
	
	if (document.all) {
		control.insertAdjacentHTML("AfterEnd",_er);
	}
	else if (document.getElementById) {
		var r = control.ownerDocument.createRange();
		r.setStartAfter(control);
		var df = r.createContextualFragment( _er );
		control.parentNode.insertBefore(df, control.nextSibling);
	}
	try	{
		control.focus();
	}
	catch(e){}
}
	
RemoveStar = function RemoveStar(control){
	var Controlsp = GetObject(control.id + 'sp');
	if (Controlsp){
		Controlsp.style.visibility = 'hidden';
	}	
}

function PreviewFile(obj)
{
	CurrentFileObject = GetObject(obj);
	if(CurrentFileObject && CurrentFileObject.value != "")
	{
		window.open(CurrentFileObject.value,'_preview',PopupWindowArguments(),true);
	}
}

var ControlWindow = null;
function ShowControls(type,sectionID)
{
	var pageUrl = "default.aspx?bridge=controls&type=" + type + (sectionID ? "&section=" + sectionID : "");
	var dialogWidth = "600";
	var dialogHeight = "350";
	var iTop=(screen.height-dialogHeight) / 2;
	var iLeft=(screen.width  - dialogWidth)  / 2;
	var sOption="location=no,menubar=no,toolbar=no,dependent=yes,dialog=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,width="+dialogWidth+",height="+dialogHeight+",top="+iTop+",left="+iLeft;
	ControlWindow=window.open(pageUrl,'controls',sOption);
	ControlWindow.focus();
}
				
addEvent = function(el, evname, func) {
	if (Browser.isIE) {
		el.attachEvent("on" + evname, func);
	} else {
		el.addEventListener(evname, func, true);
	}
};

removeEvent = function(el, evname, func) {
	if (Browser.isIE) {
		el.detachEvent("on" + evname, func);
	} else {
		el.removeEventListener(evname, func, true);
	}
};

function SetParam(param,title){
	window.parent.SetParameterControl(param,title);
}

function GetUrlParameter( paramName )
{
	var oRegex = new RegExp( '[\?&]' + paramName + '=([^&]+)', 'i' ) ;
	var oMatch = oRegex.exec( window.top.location.search ) ;
	
	if ( oMatch && oMatch.length > 1 )
		return oMatch[1] ;
	else
	{
		var oMatch = oRegex.exec( window.location.search ) ;
		if ( oMatch && oMatch.length > 1 )
			return oMatch[1] ;
		else
			return '' ;
	}
}

function AddScript(path)
{
	document.write('<s'+'cript language="JavaScript" src="' + path + '"></s'+'cript>');
}

function AddStyleSheet(path)
{
	document.write('<l'+'ink rel="stylesheet" type="text/css" href="' + path + '"></l'+'ink>');
}

var LastEditorObject;
function ShowEditor(objID,mode,lang)
{
	LastEditorObject = GetObject(objID);
	if(LastEditorObject)
	{
		var argument = PopupWindowArguments(800,600);
		var cWindow = window.open("AltaB2xCore/client_scripts/fckeditor/editor.html?e=t" + (mode ? "&mode=" + mode : "") + (lang ? "&lang=" + lang : ""),'htmleditor',argument,true);
		cWindow.focus();
	}
}


AddScript("AltaB2xCore/client_scripts/altatab/altatab.js");
AddStyleSheet("AltaB2xCore/client_scripts/altatab/altatab.css");
AddScript("AltaB2xCore/client_scripts/common/cookies.js");
