/**
 * In The Name of Allah, The Most Gracious, The Most Merciful
 * Version 6.1
 */
function SetScreen() {
	if (TD = $("tdForm")){
		ScreenWidth = screen.width;
		if (ScreenWidth >= 1024) {
			TD.height = "350px";
		}
	}
}

function PageLoading(){
	var f;
	SetScreen();

	if (typeof (f = GBCG('FormLoading', 'function')) == 'function' && f !== $empty) {
		f(1);
	} else {
		if (typeof (f = GBCG('FormLoading_', 'function')) == 'function' && f !== $empty) {
			f();
		}
	}
	if (typeof (f = GBCG('PageLoading_', 'function')) == 'function' && f !== $empty) {
		f();
	}
}
window.addEvent('load', PageLoading);

function GetButterflyCMSGlobals(ElementName, ElementType){
    var d = document, b = 'butterflycms.', ET;
    d.butterflycms = d.butterflycms || {};

    ET = ElementType.toLowerCase() + '_';

    return $try(function() {
        return eval('(function(){d.' + b + ET + ' = d.' + b + ET + ' ? d.' + b + ET + ' : {};' +
	'return d.' + b + ET + '.' + ElementName + ' ? d.' + b + ET + '.' + ElementName + ' : (' + ElementName + ' ? ' + ElementName + ' : $empty);})()')
    },
	$empty);
}

function GBCG(ElementName, ElementType) {
    return GetButterflyCMSGlobals(ElementName, ElementType);
}

function SetButterflyCMSGlobals(ElementName, ElementType, ElementValue) {
    var d = document, b = 'butterflycms.', ET;
    d.butterflycms = d.butterflycms || {};

    ET = ElementType.toLowerCase() + '_';

    return $try(function() {
        return eval('(function(){d.' + b + ET + ' = d.' + b + ET + ' ? d.' + b + ET + ' : {};' +
	'd.' + b + ET + '.' + ElementName + (ET != 'function_' ? ' = ElementValue' : ' = function' + ElementValue) + ';' +
	'd.' + b + ET + '.' + ElementName + ';' +
	'return d.' + b + ET + '.' + ElementName + ';})()')
    },
	$empty);
}

function SBCG(ElementName, ElementType, ElementValue){
	return SetButterflyCMSGlobals(ElementName, ElementType, ElementValue);
}

function GoTo(URL) {
	URL = PrepareUrl(URL);
	if(fnclvElement = $('_systemRequestionType')) {
		switch(fnclvElement.value) {
			case 'AJAX':
				FreezeFrame(GetWaitingFor());
				var request = new Request.HTML({url: URL, method: 'get', 'onSuccess':PageLoader, evalScripts: false}).send();
				break;
			case 'NORMAL':
				window.location = URL;
				break;
		}
	} else {
		window.location = URL;
	}
}

function GoToAHref(Evt){
	Evt = new Event(Evt);
	var A = Evt.target, Basehref, GEA;
	Evt.preventDefault();
	
	if (A && (Basehref = (GEA = GetElementAttributes(A, true)).basehref || GEA.href)){
		var Options = GEA.specs || '"Parameters": [], "Exact": false';
		Options = eval('({' + Options + '})');
		GoTo({'Address': Basehref, 'Options': Options});
	}
	return false;
}

function GoToNew(URL)
{
	var NewWindow = window.open(PrepareUrl(URL));
}

function PrepareUrl(URL){
	if (typeof URL == 'string'){
		URL = {Address: URL, Options:{Parameters: [], Exact: false}};
	}
	URL = UrlParser({'Action': 'Prepare', 'Options': {'URL': URL.Address, Options: URL.Options}});
	return URL;
}

function UrlParser(Options){
	switch(Options.Action){
		case 'Prepare':
			var ps, p, i, Found, Url = Options.Options.URL ? (Options.Options.URL + (Options.Options.URL.indexOf('?') === false ? '?' : '')).split('?') : ['', ''];
			Url[1] = Options.Options.Options.Exact ? '' : Url[1];
			ps = Options.Options.Options.Parameters;
			for(i = 0; i < ps.length; i++){
				Found = false;
				Url[1] = Url[1].replace(new RegExp('(^|&)' + ps[i].Parameter + '=[^&$]*(&|$)', 'g'), function(){
					Found = true;
					return arguments[1] + ps[i].Parameter + '=' + ps[i].Value + arguments[2];
				});
				if (!Found){
					Found = !(Url[1] += (Url[1] ? '&' : '') + ps[i].Parameter + '=' + ps[i].Value);
				}
			}
			return Url[0] + '?' + Url[1];
	}
}

function GoToNewBlank(URL)
{
	var NewWindow = window.open(PrepareUrl(URL), "", "left=40,top=30,width=800,height=600,status=1,scrollbars=1,menubar=0,toolbar=0,resizable=0");
}

function GoToNewBlankWithSize(URL, Width, Height)
{
	ScreenHeight = screen.availHeight;
	ScreenWidth = screen.availWidth;

	var Left = Math.floor((ScreenWidth - Width) / 2);
	var Top = Math.floor((ScreenHeight - Height) / 2);

	var NewWindow = window.open(PrepareUrl(URL), "", "left=" + Left + ",top=" + Top + ",width=" + Width + ",height=" + Height + ",status=1,scrollbars=1,menubar=0,toolbar=0,resizable=0");
}

function NewWindow(URL, Target, Width, Height, Top, Left, Resizable, MenuBar, ScrollBars, ToolBar, Status)
{
	return goToWindow(URL, Target, Width, Height, Top, Left, Resizable, MenuBar, ScrollBars, ToolBar, Status);
}

function goToWindow(URL, Target, Width, Height, Top, Left, Resizable, MenuBar, ScrollBars, ToolBar, Status) {
	var StatusText = '';

	if (!(Target && Target.length > 0))
	{Target = null;}

	if (Width)
	{StatusText += ',width=' + Width;}
	else
	{StatusText += ',width=800';}

	if (Height)
	{StatusText += ',height=' + Height;}
	else
	{StatusText += ',height=600';}

	if (Top)
	{StatusText += ',top=' + Top;}
	else
	{StatusText += ',top=30';}

	if (Left)
	{StatusText += ',left=' + Left;}
	else
	{StatusText += ',left=40';}

	if (Resizable)
	{StatusText += ',resizable=' + Resizable;}
	else
	{StatusText += ',resizable=yes';}

	if (MenuBar)
	{StatusText += ',menubar=' + MenuBar;}
	else
	{StatusText += ',menubar=no';}

	if (ScrollBars)
	{StatusText += ',scrollbars=' + ScrollBars;}
	else
	{StatusText += ',scrollbars=yes';}

	if (ToolBar)
	{StatusText += ',toolbar=' + ToolBar;}
	else
	{StatusText += ',toolbar=no';}

	if (Status)
	{StatusText += ',status=' + Status;}
	else
	{StatusText += ',status=no';}

	if (StatusText.length > 0)
	{
		StatusText = StatusText.substr(1);
	}

	var NewWindow_ = window.open(PrepareUrl(URL), Target, StatusText);
}

function trim(str){
	if (typeof(str) == "string")
		return str.replace(/^\s*|\s*$/,"");

//	return str.replace(/(^ +| +$)/, "");
}

function Close() {
	window.close()
}

function RandomNumber()
{
	return Math.floor(Math.random()*10000);
}

function PageLoader(pageTree, pageElements, pageHTML, pageJavaScript)
{
	window.fireEvent('beforeChange');
	$(document.getElementsByTagName('body')[0]).empty().adopt(pageTree);
//	eval(pageJavaScript);
	window.fireEvent('load');
	DefrostFrame();
}

function replaceCharAt( i_startPos, i_newChar )
{
   var i_string = this.toString();

   var result = "" ;
   result = i_string.substr( 0, i_startPos);
   result += i_newChar ;
   result += i_string.substr( i_startPos+1 );

   return result ;
}

function replaceAt( i_startPos, i_length, i_newString )
{
   var i_string = this.toString();

   var result = i_string.substr( 0, i_startPos);
   result += i_newString ;
   result += i_string.substr( i_startPos+i_length );

   return result ;
}

function stringClear()
{
	
  var i_string = this.toString();

  i_string.replace(/^\x60{1}$/g, '0');
  i_string.replace(/^\x61{1}$/g, '1');
  i_string.replace(/^\x62{1}$/g, '2');
  i_string.replace(/^\x63{1}$/g, '3');
  i_string.replace(/^\x64{1}$/g, '4');
  i_string.replace(/^\x65{1}$/g, '5');
  i_string.replace(/^\x66{1}$/g, '6');
  i_string.replace(/^\x67{1}$/g, '7');
  i_string.replace(/^\x68{1}$/g, '8');
  i_string.replace(/^\x69{1}$/g, '9');

  return i_string;
}

function swapNodes(item1, item2) {
var itemtmp = item1.cloneNode(1);
var parent = item1.parentNode;
item2 = parent.replaceChild(itemtmp,item2);
parent.replaceChild(item2,item1);
parent.replaceChild(item1,itemtmp);
itemtmp = null;
}

String.prototype.replaceCharAt = replaceCharAt;
String.prototype.replaceAt = replaceAt;
String.prototype.clear = stringClear;
//String.prototype.base64Encode = stringClear;

function base64Encode(){
	return Base64.encode(this.toString())
}

function base64Decode(){
	return Base64.decode(this.toString())
}

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function GetElementAttributes(el, LowerCase){
	el = $(el);
	LowerCase = LowerCase || false;

	var Attributes = {}, AName, i;
	if (el.attributes){
		for(i = 0; i < el.attributes.length; i++){
			AName = el.attributes[i].name;
			Attributes[LowerCase ? AName.toLowerCase() : AName] = el.attributes[i].value;
		}
	}else{
		for(i in el){
			Attributes[typeof i == 'string' ? (LowerCase ? i.toLowerCase() : i) :  i] = el[i];
		}
	}
	return Attributes;
}

function FreezeFrame(objOptions) {
	objOptions = objOptions || {};
	objOptions.content = objOptions.content || 'default';
	objOptions.imgSrc = objOptions.imgSrc || '../images/ajax-loader.gif';

	if (!$('FrameFreezer')) {
		var objScrolls = Document.getScrollSize(), F/*rameFreezer*/ = new Element('div', {id: 'FrameFreezer'}).setStyles({
			width: objScrolls.x,
			height: objScrolls.y,
			'z-index': 10000,
			position: 'absolute',
			//left: 0,
			top: 0,
			'background-color': '#23362F',
			'opacity': .6
		});
		switch (objOptions.content) {
			case 'default':
				var FloatLayer, objScroll = Window.getScroll();
				F.grab(FloatLayer = new Element('img', {id: 'FloatingAjaxLoader', src: objOptions.imgSrc}).setStyles({
					position: 'absolute',
					top: objScroll.y + (Window.getHeight() / 2) - 50,
					left: objScroll.x + (Window.getWidth() / 2) - 50
				}));
				break;
			default:
				F.grab(objOptions.content);
		}

		document.body.appendChild(F)
		KeepFreeze();
		window.addEvent('resize', KeepFreeze);
	}
}

function KeepFreeze(){
	var F = $('FrameFreezer'), w, h, objScroll = Window.getScrollSize();;
	if (F) {
		if ((h = Window.getHeight()) < objScroll.y)
			h = objScroll.y;

		if ((w = Window.getWidth()) < objScroll.x)
			w = objScroll.x;

		F.setStyles({height: h, width: w});
	}
}

function DefrostFrame(){
	var F = $('FrameFreezer');
	if (F)
		F.dispose();

	window.removeEvent('resize', KeepFreeze);
}

function ClientWidth(){
	var v=0,d=document,w=window;
	if(d.compatMode=='CSS1Compat'&&!w.opera&&d.documentElement&&d.documentElement.clientWidth){
		v=d.documentElement.clientWidth;
	}else if(d.body&&d.body.clientWidth){
		v=d.body.clientWidth;
	}else if($defined(w.innerWidth, w.innerHeight, d.heigh)){
		v=w.innerWidth;
		if(d.height>w.innerHeight)	v-=16;
	}
	return v;
}

function GetWaitingFor(objOptions) {
	objOptions = objOptions || {};
	objOptions.ImgSrc = objOptions.ImgSrc || '../images/waiting1.gif';
	return new Element('div').setStyles({width: '100%', 'text-align': 'center', 'vertical-align': 'middle'}).setStyle('height', ClientHeight()).grab(
		new Element('img', {src: objOptions.ImgSrc})
	);
}

// -- Miscellaneous --
/*
Element.implement({
	centralize: function(){
	}
})
*/
// -- 

function ClientHeight(){var v=0,d=document,w=window;if(d.compatMode=='CSS1Compat'&&!w.opera&&d.documentElement&&d.documentElement.clientHeight){v=d.documentElement.clientHeight;}else if(d.body&&d.body.clientHeight){v=d.body.clientHeight;}else if($defined(w.innerWidth, w.innerHeight, d.width)){v=w.innerHeight;if(d.width>w.innerWidth)v-=16;}return v;}
/*
function var_dump(var){
	switch(typeof var){
		case '':
	}
}
*/
function GetPosOffset(What, OffsetType) {
	var TotalOffset = (OffsetType == "left")? What.offsetLeft : What.offsetTop;
	var ParentEl = What.offsetParent;
	while (ParentEl != null) {
		TotalOffset += (OffsetType == "left")? ParentEl.offsetLeft : ParentEl.offsetTop;
		ParentEl = ParentEl.offsetParent;
	}

	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined')
		TotalOffset += (OffsetType == "left") ? document.body.leftMargin : document.body.topMargin;

	return TotalOffset;
}

function Delay(WaitTime) {
	var oStartDate = new Date(), oCurDate;
	
	do oCurDate = new Date();
	while(oCurDate - oStartDate < WaitTime);
}

function StretchDynamicElements() {
	var Width = Window.getWidth();
	var Height = Window.getHeight();
	$$('.width-stretchable-element').each(function (elem) {
		$(elem).setStyle('width', Width - 40)
	});
	$$('.height-stretchable-element').each(function (elem) {
		$(elem).setStyle('height', Height - 40)
	});
}

window.addEvent('resize', StretchDynamicElements);
window.addEvent('load', StretchDynamicElements);
/*
function dump_object(_obj) {
	var s="";
	for(var i in _obj) s += i + " * ";

	alert(s);
}
*/