/*
 * All ajax call specified in variables
 */

/**
 * Mouse event catcher
 */
var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0
var tempY = 0

/**
 * Default ajax scripts vars
 */
var host = window.location.host;
var strAjaxShowComponentScreen      = 'http://' + host + '/ac_framework/scripts/ajax/component_showscreen.php?intComponentInstanceId=';
var strAjaxExecuteCommand           = 'http://' + host + '/ac_framework/scripts/ajax/execute_command.php?intComponentInstanceId=';
var strAjaxGetContextMenuCommand    = 'http://' + host + '/ac_framework/scripts/ajax/component_getcontextmenu.php?intComponentInstanceId=';
document.onclick = funCloseContextMenu;

/**
 * Window array with all components ContextMenu's
 *
 */
window.arrContextMenus = new Array();


/**
*	funShowComponentInstanceScreen will create an overlay on the website and add
*   a viewport for the edit strMode of a component and after that a ajax
*   call will be called to fill the viewport with content
*
*	params intInstanceId
*	params strQueryString
*	params strAction (edit, new)
*	return void;
*/
function funShowComponentInstanceScreen(intInstanceId, strQueryString, strAction){
	funCreateViewport(intInstanceId, strQueryString, strAction);
}


/**
* Create viewport for the website.
* The viewport is an div in the middle of the screen where you can edit data from a component
*
* Params: intInstanceId
*/
function funCreateViewport(intInstanceId, strQueryString, strAction) {
    var browserName=navigator.appName;

    // OVERLAY
	// Create div overlay
    var temp_overlay = document.getElementById('overlay_id');
    if (!temp_overlay) {
        var overlay = document.createElement('div');
    	overlay.id = 'overlay_id';

        // Get browser with and height
        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;
        }

    	overlay.style.backgroundColor	 	= '#000';
        overlay.style.display               = "block";
    	overlay.style.visibility            = "visible";
    	overlay.style.position 				= 'absolute';
    	overlay.style.overflow 				= 'hidden';
    	overlay.style.top 					= '0px';
    	overlay.style.left 					= '0px';
    	overlay.style.width 				= (myWidth) + "px";
    	overlay.style.height 				= 3*(myHeight) + "px";
    	overlay.style.zIndex				= '998';

        funSetOpacity(overlay, 1);

    	// Append overlay to body
    	document.body.appendChild(overlay);
    } else {
        temp_overlay.style.display        = "block";
    	temp_overlay.style.visibility     = "visible";
    }

    // VIEWPORT
    var temp_viewport = document.getElementById('viewport_id');
    if (!temp_viewport) {
        var viewport = document.createElement("iframe");
        viewport.src                    = strAjaxShowComponentScreen + intInstanceId + '&strAction=' + strAction + '&' + strQueryString;
    	viewport.id                     = "viewport_id";
    	viewport.style.position 		= 'absolute';
    	viewport.style.overflow         = 'hidden';
    	viewport.style.whiteSpace       = 'Nowrap';
    	viewport.style.width 			= 800  + "px";
    	viewport.style.left 		    = (myWidth / 2) - (800 / 2)  + "px";
      	viewport.style.top     			= (myHeight / 2) - (500 / 2)  + "px";
    	viewport.style.backgroundColor 	= '#F0F0EE';
    	viewport.style.backgroundImage  = "url(http://bulk/ac_framework/images/indicator.gif)";
    	viewport.style.backgroundPosition = '50% 50%';
    	viewport.style.backgroundRepeat = 'no-repeat';
    	viewport.style.border		 	= '5px #CCC inset';
    	viewport.style.zIndex 			= '999';

        if (browserName=="Netscape") {
        	viewport.style.height 			= 485  + "px";
        }else{
            if (browserName=="Microsoft Internet Explorer") {
            	viewport.style.height 			= 505  + "px";
            }else{
            	viewport.style.height 			= 485  + "px";
            }
        }

    	document.body.appendChild(viewport);
    } else {
        temp_viewport.style.display        = "block";
    	temp_viewport.style.visibility     = "visible";
        temp_viewport.src                  = strAjaxShowComponentScreen + intInstanceId + '&strAction=' + strAction + '&' + strQueryString;
    }
}

/**
 * ExecuteCommand is a function that will do another ajax call to execute a components action which must be given in the parameters.
 * ExecuteCommand is used with TinyMCE editor and the callback produces a double function call.
 * We use the boolean isCalled to catch the second call.
 *
 * @return FALSE disable the submit of the form (we want ajax to do this)
 */
function funExecuteCommand(strFormId, strAction, intInstanceId, strQueryString) {
    var host = window.location.host;
    var mainscreen = window.parent;
    var viewport = mainscreen.document.getElementById('viewport_id');
    var overlay = mainscreen.document.getElementById('overlay_id');
    var objCompResponder;
    var query_string = '';

    // Filter intComponentInstanceId from query string, only when query string is set
    if (strQueryString !== undefined) {
        query_string = strQueryString.replace('intComponentInstanceId='+intInstanceId+'&', '');
    }

    new Ajax.Request(strAjaxExecuteCommand + intInstanceId + '&' + query_string,
      {
        method      : 'post',
        parameters  : $(strFormId).serialize(true),
        onSuccess: function(transport){
           
             try {
             //alert('objCompResponder = ' + transport.responseText);
             //alert(strAjaxExecuteCommand + intInstanceId + '&' + query_string);
             eval('objCompResponder = ' + transport.responseText);
          } catch (objException){
             alert('JS[AJAX] Exception raised (component_actions):\n' + objException.message + '\n received:\n' + transport.responseText);
          };

          // Show message from component execCommand, only when error occurs
          if (objCompResponder.strMessage != '' ) {
              alert(objCompResponder.strMessage);
          }

          // ArrUpdateElement
          if (objCompResponder.arrUpdateElement['strContainerId'] != '' ) {
              funUpdate(mainscreen, objCompResponder.arrUpdateElement['strClassName'], objCompResponder.arrUpdateElement['strContainerId'], objCompResponder.arrUpdateElement['intInstanceId'], objCompResponder.arrUpdateElement['mixValue'], query_string);
          } 

          // Close function
          if (objCompResponder.funClose != '' ) {
              funCloseEditScreenNoSave();
          }
        },
        onFailure: function(){
            alert('There\'s something wrong with the request.\n Please try again later.\n(check your internet connection)')
        }
      });
}

/**
 * Update container on mainscreen
 */
function funUpdate(mainscreen, strClassName, strContainerId, intInstanceId, strData, strQueryString)
{
    var container = mainscreen.document.getElementById(strContainerId);
    container.innerHTML = strData;
}

/**
 * Function to hide elements
 */
function funHideElement(objElement)
{
    if (objElement) {
        objElement.style.display = "none";
    	objElement.style.visibility = "hidden";
    }
}

/**
 * Function to show elements
 */
function funShowElement(objElement)
{
    if (objElement) {
        objElement.style.display = "display";
    	objElement.style.visibility = "visible";
    }
}

/**
 * Function to close the overlay and viewport at ones, without saving any content
 * Used for cancel or close operation
 */
function funCloseEditScreenNoSave()
{
    var mainscreen = window.parent;
    var viewport    = mainscreen.document.getElementById('viewport_id');
    var overlay     = mainscreen.document.getElementById('overlay_id');
    var contextmenu = mainscreen.document.getElementById('contextmenu_id');
    funHideElement(viewport);
    funHideElement(overlay);
    funHideElement(contextmenu);
}

/*
 * Function to display a components instance container context menu
 *
 * @param: objEvent
 */
function funShowComponentInstanceContextMenu(objEvent, intInstanceId)
{
    var blnLoadContextMenu = true;
    var objContextMenu = document.getElementById('contextmenu_id');
    var objJsonContextMenu;

    // Check event
    if (typeof objEvent != "undefined") {
        objContainer = objEvent.currentTarget;

        if (typeof objEvent.pointerX == 'function') {
            window.mouseY = objEvent.pointerY(objEvent);
            window.mouseX = objEvent.pointerX(objEvent);
        } else {
            window.mouseY = objEvent.y;
            window.mouseX = objEvent.x;
        }
    } else if (typeof window.event != "undefined") {
        alert('possible other browser: todo set event handler');
    } else if (typeof this.event != "undefined") {
        alert('possible other browser: todo set event handler');
    } else {
        alert('unknown browser!');
    }

    // Check if component instance contextmenu already been loaded, if so only show contextmenu
    if ((typeof window.arrContextMenus[intInstanceId] != "undefined") || (typeof window.arrContextMenus[intInstanceId] == "object")) {
        // Fill the context menu from the window array
        funShowContextMenu(window.arrContextMenus[intInstanceId], objContainer, intInstanceId);
        blnLoadContextMenu = false;
    }

    // Get context menu (ajax call) from component instance
    if (blnLoadContextMenu == true) {
        new Ajax.Request(strAjaxGetContextMenuCommand + intInstanceId,
          {
            method      : 'post',
            onSuccess: function(transport){
                try {
                 // alert('json = ' + transport.responseText);
                 eval('objJsonContextMenu = ' + transport.responseText);

                 // Fill window array with the instance id
                 window.arrContextMenus[intInstanceId] = objJsonContextMenu;

                 // Show context menu
                 funShowContextMenu(objJsonContextMenu, objContainer, intInstanceId);
              } catch (objException){
                 alert('Exception raised (component_getcontextmenu):\n' + objException.message + '\n received:\n' + transport.responseText);
              };

            },
            onFailure: function(){
                alert('There\'s something wrong with the request.\n Please try again later.\n(check your internet connection)')
            }
          });
    }

    return false;
}

/*
 * Function to display a components instance container context menu
 *
 * @param: objContextMenu (JSON)
 * @param: objContainer
 */
function funShowContextMenu(objJsonContextMenu, objContainer, intInstanceId)
{
    // Set ContextMenu
    var TempContextMenu = document.getElementById('contextmenu_id');
    if (!TempContextMenu) {
        var ContextMenu = document.createElement('div');
        ContextMenu.id  = 'contextmenu_id';
        ContextMenu.style.display     = 'none';

    	//objContainer.appendChild(ContextMenu);
    	document.body.appendChild(ContextMenu);
    } else {
        TempContextMenu.parentNode.removeChild(TempContextMenu);
        var ContextMenu = document.createElement('div');
        ContextMenu.id  = 'contextmenu_id';
        ContextMenu.style.display     = 'none';

        document.body.appendChild(ContextMenu);
    }
    var objContextMenu = document.getElementById('contextmenu_id');

    // Set ContextMenu properties
    objContextMenu.className                  = 'noclass';
    objContextMenu.style.left                 = getMousePos('x') + "px";
    objContextMenu.style.top                  = getMousePos('y') + "px";
    objContextMenu.style.width                = 100 + "px";
    objContextMenu.style.position             = 'absolute';
    objContextMenu.style.display              = 'block';
	objContextMenu.style.backgroundColor 	  = '#F5F5F5';
	objContextMenu.style.border		 	      = '1px #979797 solid';
	objContextMenu.style.borderRight	      = '2px #666666 solid';
	objContextMenu.style.borderBottom	      = '2px #666666 solid';
	objContextMenu.style.zIndex 			  = '500';
	objContextMenu.style.textAlign            = 'left';
	objContextMenu.style.padding              = '2px';
	objContextMenu.style.paddingRight         = '3px';
	objContextMenu.style.paddingRight         = '3px';

    // Build contextmenu
    funBuildContextMenu(objJsonContextMenu.arrMenuItems, objContextMenu, intInstanceId);
}

function funBuildContextMenu(arrMenuItems, objContextMenu, intInstanceId)
{
    // Create table for inner htmlk context menu
    var strHtml = '<table cellspacing="0" cellpadding="3" style="background-color : #F0F0F0; width : 100px;">';
    //strHtml += '<tbody>';

    for(var i=0; i < arrMenuItems.length; i++) {
        var objItem = arrMenuItems[i];

        var strLinkId       = 'link_id_' + i;
        var strColor1       = "#336699";
        var strColor2       = "#F0F0F0";
        var strLinkColor1   = "#FFFFFF";
        var strLinkColor2   = "#000000";
        var strTrId         = "menuitem_" + i;

        strHtml += '<tr id="'+strTrId+'" onmouseover="changecolor(\'' + strTrId + '\', \'' + strColor1 + '\', \'' +strLinkId+'\', \'' + strLinkColor1 + '\')" onmouseout="changecolor(\'' + strTrId + '\', \'' + strColor2 + '\', \'' +strLinkId+'\', \'' + strLinkColor2 + '\')" onclick="'+objItem.strHref+'">';
        strHtml += '<td style="border-bottom : 1px #E0E0E0 solid; width : 10px;">';
        strHtml += '<img width="20" height="14" src="'+ objItem.strImage +'">';
        strHtml += '</td>';
        strHtml += '<td style="border-bottom : 1px #E0E0E0 solid;">';
        strHtml += '<a href="'+objItem.strHref+'" id="'+strLinkId+'" title="'+objItem.strTooltip+'" target="_self" style="color : #000000; font-size: 11px; font-weight : normal; padding-bottom : 5px; text-decoration: none;">' + objItem.strCaption + '</a>';
        strHtml += '</td>';
        strHtml += '</tr>';
	}
    strHtml += '</table>';

	// Add table to contextmenu through html
    objContextMenu.innerHTML = strHtml;

	return false;
}


function setStyle(object, strStyletext)
{
    if (object.style.setAttribute) {
        object.style.setAttribute("cssText", strStyletext);
    }else{
        object.setAttribute("style", strStyletext);
    }
}


function changecolor(strDivId, strColor, strLinkId, strLinkColor) {
    var div = document.getElementById(strDivId);
    div.style.backgroundColor   = strColor;

    var divLink = document.getElementById(strLinkId);
    divLink.style.color         = strLinkColor;
}


function funSetOpacity(element, intfactor)
{
    var browserName=navigator.appName;

    if (intfactor == 1)
    {
        if (browserName=="Netscape") {
        	element.style.filter           = 'alpha (opacity = 50);';
        	element.style.MozOpacity       = '0.40;';
        	element.style.opacity          = '0.75;';
        }else{
            if (browserName=="Microsoft Internet Explorer") {
            	element.style.filter       = 'alpha (opacity = 70);';
            	element.style.opacity      = '0.95;';
            }else{
            	element.style.filter       = 'alpha (opacity = 60);';
            	element.style.opacity      = '0.75;';
            }
        }
    }
}

/**
 * Function to close the context menu
 */
function funCloseContextMenu()
{
    try {
        var objElement = document.getElementById('contextmenu_id');
        objElement.parentNode.removeChild(objElement);
    } catch(e) {

    }
}


// Main function to retrieve mouse x-y pos.s	
function getMouseXY(e) {
	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft
		tempY = event.clientY + document.body.scrollTop
	} else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX
		tempY = e.pageY
	}  
	
	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0}
	if (tempY < 0){tempY = 0}  
}


function getMousePos(strPosXY) 
{
	if (strPosXY == 'x') {
		return tempX;
	}
	if (strPosXY == 'y') {
		return tempY;
	}
}