
/**
 * Rapid object finder
 */
function $(object)
{
	return document.getElementById(object);
}

/**
 * Identify pixel position [left, top] of any object on the page
 */
function findPosition(obj)
{
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
    	do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
    	} while (obj = obj.offsetParent);
    	var position = new Object();
    	position.left = curleft;
    	position.top = curtop;
    	position.x = position.left;
    	position.y = position.top;
    	return position;
	}
}

/**
 * Jump to uri only if it is not void.
 */
function gotoUri(uri)
{
    if (uri != "" && uri != "#") {
        window.location = uri;
    }
}

/**
 * Add a replace all method to string
 */
String.prototype.replaceAll = function(replaceRegEx, replaceWith){
    var result = this;
    var updatedResult;
    do {
        updatedResult = result;
        result = result.replace(replaceRegEx, replaceWith);
    } while (updatedResult != result);
    return result;
}

/**
 * Add a trim function to string
 */
String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/**
 * Convert decimal to hexadecimal
 */
function dec2hex(decimal)
{
    return decimal.toString(16);
}

/**
 * Returns the size of the whole page, and the size of the window
 */
function getPageSize()
{

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

/**
 * Retrieve mouse coordinates relative to document
 */
function mouseCoordinates(event)
{
	if (event.pageX || event.pageY) {
		return {x:event.pageX, y:event.pageY};
	}
	return {
		x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:event.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

/**
 * Error function
 */
function error(message)
{
    alert(message);
}

/**
 * Checks whether the param string is a valid email address or not
 */
function isEmail(testString)
{
    var filter = new RegExp("^([a-zA-Z0-9_\\.\\-])+\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z]{2,6})$");
    if (filter.test(testString)) {
        return true;
    } else {
        return false;
    }
}

function getAsyncDocumentByUrl(url, callbackFunction)
{
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('GET', url, true);
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            if (callbackFunction) {
                callbackFunction(self.xmlHttpReq.responseText);
            }
        }
    }
    self.xmlHttpReq.send("");
}

function _aponAnimation(startFrame, endFrame, interval, curve, frameFunction)
{
    this.startFrame    = startFrame;
    this.endFrame      = endFrame;
    this.interval      = interval;
    this.curve         = curve;
    this.frameFunction = frameFunction;
    this.direction = (startFrame < endFrame ? 1 : -1);
    if (!_aponAnimation.animationList) {
        _aponAnimation.animationList = new Array();
    }
    this.animationId = _aponAnimation.animationList.length;
    _aponAnimation.animationList[this.animationId] = this;
}

_aponAnimation.prototype.start = function ()
{
    this.animateFrame(this.startFrame);
}

_aponAnimation.prototype.animateFrame = function (frame)
{
    this.frameFunction(frame);
    if ((this.direction < 0 && frame > this.endFrame) || (this.direction > 0 && frame < this.endFrame)) {
        //increase the frame and call animation again
        if (!this.curve || this.curve == "linear") {
            frame = frame + this.direction
        } else {
            //todo: other curves like logarithmic and exponential
        }
        setTimeout("_aponAnimation.animationList[" + this.animationId + "].animateFrame(" + frame + ");", this.interval);
    }
}

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

/**
 * Convert all applicable characters to HTML entities
 */
function htmlentities (string, quote_style) {
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();

    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }

    return tmp_str;
}

/**
 * Returns the internal translation table used by htmlspecialchars and htmlentities
 */
function get_html_translation_table(table, quote_style) {
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};

    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');

    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }

    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        if (useQuoteStyle != 'ENT_NOQUOTES') {
            entities['34'] = '&quot;';
        }
        if (useQuoteStyle == 'ENT_QUOTES') {
            entities['39'] = '&#039;';
        }
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
	    entities['38']  = '&amp;';
        if (useQuoteStyle != 'ENT_NOQUOTES') {
            entities['34'] = '&quot;';
        }
        if (useQuoteStyle == 'ENT_QUOTES') {
            entities['39'] = '&#039;';
        }
	    entities['60']  = '&lt;';
	    entities['62']  = '&gt;';
	    entities['160'] = '&nbsp;';
	    entities['161'] = '&iexcl;';
	    entities['162'] = '&cent;';
	    entities['163'] = '&pound;';
	    entities['164'] = '&curren;';
	    entities['165'] = '&yen;';
	    entities['166'] = '&brvbar;';
	    entities['167'] = '&sect;';
	    entities['168'] = '&uml;';
	    entities['169'] = '&copy;';
	    entities['170'] = '&ordf;';
	    entities['171'] = '&laquo;';
	    entities['172'] = '&not;';
	    entities['173'] = '&shy;';
	    entities['174'] = '&reg;';
	    entities['175'] = '&macr;';
	    entities['176'] = '&deg;';
	    entities['177'] = '&plusmn;';
	    entities['178'] = '&sup2;';
	    entities['179'] = '&sup3;';
	    entities['180'] = '&acute;';
	    entities['181'] = '&micro;';
	    entities['182'] = '&para;';
	    entities['183'] = '&middot;';
	    entities['184'] = '&cedil;';
	    entities['185'] = '&sup1;';
	    entities['186'] = '&ordm;';
	    entities['187'] = '&raquo;';
	    entities['188'] = '&frac14;';
	    entities['189'] = '&frac12;';
	    entities['190'] = '&frac34;';
	    entities['191'] = '&iquest;';
	    entities['192'] = '&Agrave;';
	    entities['193'] = '&Aacute;';
	    entities['194'] = '&Acirc;';
	    entities['195'] = '&Atilde;';
	    entities['196'] = '&Auml;';
	    entities['197'] = '&Aring;';
	    entities['198'] = '&AElig;';
	    entities['199'] = '&Ccedil;';
	    entities['200'] = '&Egrave;';
	    entities['201'] = '&Eacute;';
	    entities['202'] = '&Ecirc;';
	    entities['203'] = '&Euml;';
	    entities['204'] = '&Igrave;';
	    entities['205'] = '&Iacute;';
	    entities['206'] = '&Icirc;';
	    entities['207'] = '&Iuml;';
	    entities['208'] = '&ETH;';
	    entities['209'] = '&Ntilde;';
	    entities['210'] = '&Ograve;';
	    entities['211'] = '&Oacute;';
	    entities['212'] = '&Ocirc;';
	    entities['213'] = '&Otilde;';
	    entities['214'] = '&Ouml;';
	    entities['215'] = '&times;';
	    entities['216'] = '&Oslash;';
	    entities['217'] = '&Ugrave;';
	    entities['218'] = '&Uacute;';
	    entities['219'] = '&Ucirc;';
	    entities['220'] = '&Uuml;';
	    entities['221'] = '&Yacute;';
	    entities['222'] = '&THORN;';
	    entities['223'] = '&szlig;';
	    entities['224'] = '&agrave;';
	    entities['225'] = '&aacute;';
	    entities['226'] = '&acirc;';
	    entities['227'] = '&atilde;';
	    entities['228'] = '&auml;';
	    entities['229'] = '&aring;';
	    entities['230'] = '&aelig;';
	    entities['231'] = '&ccedil;';
	    entities['232'] = '&egrave;';
	    entities['233'] = '&eacute;';
	    entities['234'] = '&ecirc;';
	    entities['235'] = '&euml;';
	    entities['236'] = '&igrave;';
	    entities['237'] = '&iacute;';
	    entities['238'] = '&icirc;';
	    entities['239'] = '&iuml;';
	    entities['240'] = '&eth;';
	    entities['241'] = '&ntilde;';
	    entities['242'] = '&ograve;';
	    entities['243'] = '&oacute;';
	    entities['244'] = '&ocirc;';
	    entities['245'] = '&otilde;';
	    entities['246'] = '&ouml;';
	    entities['247'] = '&divide;';
	    entities['248'] = '&oslash;';
	    entities['249'] = '&ugrave;';
	    entities['250'] = '&uacute;';
	    entities['251'] = '&ucirc;';
	    entities['252'] = '&uuml;';
	    entities['253'] = '&yacute;';
	    entities['254'] = '&thorn;';
	    entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }

    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }

    return histogram;
}

/**
 * Checks if a variable is defined
 */
function isDefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}function createAjaxRequest(uri, functionArguments)
{
    var ajaxRequest = new Object();
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			ajaxRequest.request = new XMLHttpRequest();
        } catch(e) {
			ajaxRequest.request = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	ajaxRequest.request = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		ajaxRequest.request = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		ajaxRequest.request = false;
        	}
		}
    }
	if(ajaxRequest.request) {
		//get the function parameters
		var params = "";
		var paramCount = 0;
		for(var i = 0; i < functionArguments.length; i++) {
			if (typeof(functionArguments[i]) == "function") {
				//the callback function
				ajaxRequest.callback = functionArguments[i];
			} else {
				params = params + "&ajaxArg" + paramCount + "=" + encodeURIComponent(encodeParam(functionArguments[i]));
				paramCount++;
			}
		}
		//catch the response with a function
		ajaxRequest.request.onreadystatechange = function ()
        {
        	var request = ajaxRequest.request;
        	if (request.readyState == 4) {
        		if (request.status == 200) {
        			var responseText = request.responseText;
    				var originalResponseText = responseText;
        			//detect separator (first line)
        			var separator = "" + responseText.match("^==[0-9a-fA-f]{32}==\n");
        			if (separator != "") {
        				var response = new Object();
        				responseText = responseText.substring(separator.length);
        				var separatorPosition = responseText.indexOf(separator);
        				//extract response text
        				response.text = responseText.substring(0, separatorPosition);
        				//find the response value
        				responseText = responseText.substring(separatorPosition + separator.length);
        				var separatorPosition = responseText.indexOf(separator);
        				if (separatorPosition == -1) {
        				    responseValueText = responseText;
        				    resposneText = "";
        				} else {
        				    responseValueText = responseText.substring(0, separatorPosition);
                            responseText = responseText.substring(separatorPosition + separator.length);
        				}
        				try {
        				    eval("var responseValue = " + responseValueText + ";");
        				} catch (e) {
        				    alert("Fatal error in response message!\n" + originalResponseText);
        				    return;
        				}
        				response.value = responseValue;
                        //find the session code
                        var separatorPosition = responseText.indexOf(separator);
                        if (separatorPosition != -1) {
                            response.code = responseText.substring(0, separatorPosition);
                            //find the fingerprint
                            response.fingerprint = responseText.substring(separatorPosition + separator.length);

            				response.getDebugUri = function()
            				{
            					if (this.code != "") {
            						return "{#APON_URI_WORKFLOW}log?session=" + response.code.substring(0, 32) + "&fingerprint=" + response.code.substring(32,34);
            					} else {
            						return "";
            					}
            				}
                        }

        				response.openDebugUri = function()
        				{
        					var debugUri = this.getDebugUri();
        					if (debugUri != "") {
        						window.open(debugUri);
        					}
        				}

        				if (ajaxRequest.callback) {
        					ajaxRequest.callback(response);
        				}
        			}
        		}
        	}
        }

        //do the actual call
		ajaxRequest.request.open("POST", uri, true);
		ajaxRequest.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		ajaxRequest.request.send(params);
	}
	return ajaxRequest;
}



function encodeParam(value) {
	//parameter values
	var serializedValue = "";
	if (value == null) {
		serializedValue = "N;";
	} else if (typeof value == "boolean") {
		serializedValue = "b:" + (value ? "1" : "0") + ";";
	} else if (typeof value == "number") {
		serializedValue = "d:" + value + ";";
	} else if (typeof value == "string") {
	    var escapedValue = value.replace("\\", "\\\\");
	    var escapedValue = escapedValue.replace("\"", "\\\"");
	    var escapedValue = escapedValue.replace("\n", "\\n");
	    var escapedValue = escapedValue.replace("\r", "\\r");
		serializedValue = "s:\"" + escapedValue + "\";";
	} else if (typeof value == "object") {
		serializedValue  = ":{";
		var size = 0;
		for(key in value) {
			size++;
			serializedValue += encodeParam(key);
			serializedValue += encodeParam(value[key]);
		}
		serializedValue = "a:" + size + serializedValue + "}";
	} else {
		//unknown types are considered null
		serializedValue = "N;";
	}
	return serializedValue;
}

function utf8DecodedStringLength(string)
{
    var decodedLength = 0;
    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            decodedLength++;
        } else if((c > 127) && (c < 2048)) {
            decodedLength += 2;
        } else {
            decodedLength += 3;
        }
    }
    return decodedLength;
}/**
 * Displays the privacy policy over the current site
 */
function _aponShowPrivacyPolicy()
{
    _aponShowLegalLightbox();
    $("_aponPrivacyPolicyTitle").style.display = "block";
    $("_aponLightboxPageContent").innerHTML = "Loading...";
    getAsyncDocumentByUrl("/content/html/privacy_policy.html", _aponShowPrivacyPolicyCallback);
}

function _aponShowPrivacyPolicyCallback(text)
{
    var lightbox = $("_aponLightboxPageContent");
    lightbox.innerHTML = text;
    var pageSize = getPageSize();
    document._aponCourtain.style.height = (pageSize[1] + 10) + "px";
}

/**
 * Displays the terms of use over the current site
 */
function _aponShowLegalNotice()
{
    _aponShowLegalLightbox();
    $("_aponLegalNoticeTitle").style.display = "block";
    $("_aponLightboxPageContent").innerHTML = "Loading...";
    getAsyncDocumentByUrl("/content/html/legal_notice.html", _aponShowPrivacyPolicyCallback);
}

function _aponShowLegalLightbox()
{
    var courtain = _aponGetCourtain();
    courtain.style.display = "block";
    courtain.style.opacity = "0";
    var courtainFrameFunction = function (frame) {
        var courtain = document._aponCourtain;
        if (document.all) {
            //only IE
            courtain.style.filter = "alpha(opacity=" + (frame * 10) + ")";
        } else {
            courtain.style.opacity = (frame / 40);
        }
        window.scroll(0, (document.body.scrollTop / 1.2));
    }
    var courtainAnimation = new _aponAnimation(10, 32, 50, "linear", courtainFrameFunction);
    courtainAnimation.start();
    var lightbox = $("_aponLightbox");
    lightbox.style.display = "block";
}

function _aponGetCourtain()
{
    if (!document._aponCourtain) {
         document._aponCourtain = $("_aponCourtain");
         var pageSize = getPageSize();
         document._aponCourtain.style.height = pageSize[1] + "px";
    }

    return document._aponCourtain;
}

function _aponRaiseCourtain()
{
    document._aponCourtain.style.display = "none";
    var lightbox = $("_aponLightbox");
    lightbox.style.display = "none";
    $("_aponPrivacyPolicyTitle").style.display = "none";
    $("_aponLegalNoticeTitle").style.display = "none";
    $("_aponContentManagerLogin").style.display = "none";
}

function _aponShowContentManagerLogin()
{
    _aponShowLegalLightbox();
    $("_aponContentManagerLogin").style.display = "block";
    if (!_aponShowContentManagerLogin.alreadyLoggedIn) {
        $("_aponLightboxPageContent").innerHTML = "Accessing <span class='_aponLogo' style='font-size: 12px'>ap<em>/</em>on</span>...";
        getAsyncDocumentByUrl("/workflow/content_management/login_screen?requestId=bc8636f8b75ad29c9429fa482502e8b2", _aponShowContentManagerLoginCallback);
    } else {
        _aponShowContentManagerLoginCallback(false);
    }
}


function _aponShowContentManagerLoginCallback(text)
{
    var lightbox = $("_aponLightboxPageContent");
    if (text != false) {
        lightbox.innerHTML = text;
        _aponShowContentManagerLogin.alreadyLoggedIn = true;
        _aponShowContentManagerLogin.loginForm = text;
    } else {
        lightbox.innerHTML = _aponShowContentManagerLogin.loginForm;
    }
    var pageSize = getPageSize();
    document._aponCourtain.style.height = pageSize[1] + "px";
    $("_aponContentManagementLogin").style.display = "block";
    $("_aponContentManagementPasswordReminder").style.display = "none";
}

function _aponShowPasswordReminder()
{
    $("_aponContentManagementLogin").style.display = "none";
    $("_aponContentManagementPasswordReminder").style.display = "block";
    $("_aponContentManagerPasswordReminderForm").style.display = "block";
    $("_aponContentManagerPasswordReminderMessage").style.display = "none";
}

function _aponContentManagementRemindPassword()
{
    if (isEmail($("_aponContentManagementEmail").value)) {
        $("_aponPasswordReminder").submit();
    } else {
        alert("Please enter a valid email value");
    }
}

function _aponContentManagementRemindPasswordCallback()
{
    $("_aponContentManagerPasswordReminderForm").style.display = "none";
    $("_aponContentManagerPasswordReminderMessage").style.display = "block";
}

function _aponShowContentManagementLoginForm()
{
    $("_aponContentManagementLogin").style.display = "block";
    $("_aponContentManagementPasswordReminder").style.display = "none";
}

function _aponGetTextboxFocusedState(textbox)
{
    if (!_aponGetTextboxFocusedState.textboxes) {
        _aponGetTextboxFocusedState.textboxes = new Array();
    }
    var enabled = false;
    if (_aponGetTextboxFocusedState.textboxes[textbox.id]) {
        enabled = _aponGetTextboxFocusedState.textboxes[textbox.id];
    }
    _aponGetTextboxFocusedState.textboxes[textbox.id] = enabled;
    return enabled;
}

function _aponFocusTextbox(textbox)
{
    var enabled = _aponGetTextboxFocusedState(textbox);
    if (!enabled) {
        textbox.value = "";
        textbox.style.color = "black";
        _aponGetTextboxFocusedState.textboxes[textbox.id] = true;
    }
}

function _aponUnfocusTextbox(textbox, defaultText)
{
    var enabled = _aponGetTextboxFocusedState(textbox);
    if (enabled && textbox.value == "") {
        textbox.value = defaultText;
        textbox.style.color = "#bfbfbf";
        _aponGetTextboxFocusedState.textboxes[textbox.id] = false;
    }
}

function _aponFocusPassword(textbox, passwordbox)
{
    if (passwordbox.style.display == "none") {
        textbox.style.display = "none";
        passwordbox.style.display = "inline";
        passwordbox.value = "";
        passwordbox.focus();
    }
}

function _aponUnfocusPassword(textbox, passwordbox)
{
    if (passwordbox.value == "") {
        textbox.style.display = "inline";
        passwordbox.style.display = "none";
    }
}

function _aponContentManagerLoginSuccess()
{
    $("_aponContentManagementLoginError").style.display = "none";
    window.location = '/';
}

function _aponContentManagerLoginFail()
{
    $("_aponContentManagementLoginError").style.display = "inline";
}


/**
 * inner !
 */

var ApOnWebpart = new Object();

/**
 * calls
 */
ApOnWebpart.putInnerHTML = function (webpart, branch, instance, additionalData, target)
{
	if (typeof(target) == "function") {
	   var callbackFunction = target;
	} else {
	   var callbackFunction = function (response)
	   {
           target.innerHTML = response.text;
	   }
	}
    var ajaxRequest = createAjaxRequest("/framework/inner/ajax_call.php?requestId=bc8636f8b75ad29c9429fa482502e8b2", [webpart, branch, instance, additionalData, callbackFunction]);
}
