
/**
 * Common JavaScript functions for
 *   
 * CPLIB - CorePublish 
 * 
 * Written by 
 * Arve Skjørestad 
 * CoreTrek AS
 * 
 * 
 */

// variable declarations
var cp2_loaded = false;
var cp2_keywordlayer;
var x;
var y;


/***************** Common functions. ********************************/

/*
  	function to init 
*/
function cp2_init()
	{
	// Mouse position capture
	ns4 = document.layers?true:false;
	ns5 = (document.getElementById && !document.all)?true:false;
	ie5 = document.all?true:false;
	ie4 = (!document.getElementById && document.all)?true:false;
	
	if(ns4)
	 document.captureEvents(Event.MOUSEMOVE);
	
	document.onmousemove=catchXY;

	// setting up keyword layer
	cp2_keywordlayer = new ct_layer("cp2keywordlayer");

	// Tell that document is loaded.
	cp2_loaded = true;
	}

// Calling the init function.
window.onload = cp2_init;
document.onclick = cp2_keywords_hide;

var cpNavigatorUserAgent = navigator.userAgent.toLowerCase() ;
var cpNavigatorUserAgentInfo = {
    isIE     : (cpNavigatorUserAgent.indexOf('msie')>-1),
    isIE7    : (cpNavigatorUserAgent.indexOf('msie 7')>-1),
    isGecko  : (cpNavigatorUserAgent.indexOf('gecko/')>-1),
    isSafari : (cpNavigatorUserAgent.indexOf('safari')>-1),
    isOpera  : (cpNavigatorUserAgent.indexOf('opera')>-1),
    isMac    : (cpNavigatorUserAgent.indexOf('macintosh')>-1)
};

/**
 * Function that reads a cookies value. Returns null if the requested cookie is not found
 */
function cpReadCookie(cookieName){
    cookieName += '=';
    var cookies = document.cookie.split(';');
    for (var i=0; i<cookies.length; i++){
        var cookie = cookies[i];
        while (cookie.charAt(0)==' ') cookie = cookie.substr(1);
        if (cookie.indexOf(cookieName) == 0) return cookie.substr(cookieName.length);
    }
    return null;
}

/*
	This is a function to catch the x and y coordinates of the mouse
*/
function catchXY(e)
   {
   // capture click coordinates
   x=(ns4 || ns5)?e.pageX:event.x+document.body.scrollLeft;
   y=(ns4 || ns5)?e.pageY:event.y+document.body.scrollTop;
  // window.status= "x:"+x+" y:"+y;
   }


/*
  function to easy open an window
*/
function ct_win(win_url,height,width, props) {
	win_name = "ct_win";
    if (props &&  props.length > 1 ) {
        win_props = props ;
    } else {
        win_props ="height="+height+",width="+width+",screenX=400,screenY=100";
    }
	window.open(win_url,win_name,win_props);
}


/**
*   function that returns the position for the given element.
*
*
*
*/
function getAbsoluteElementPosition(el){
    var origEl = el;
    for (var lx=0,ly=0;el!=null;
        lx+=el.offsetLeft-((el.offsetParent && el.offsetParent.offsetParent)?el.offsetParent.scrollLeft:0),
        ly+=el.offsetTop-((el.offsetParent && el.offsetParent.offsetParent)?el.offsetParent.scrollTop:0),
        el=el.offsetParent);
    el = origEl;
    if (el && !document.all) {
        do {
            if (el.parentNode && !(el.parentNode.tagName && el.parentNode.tagName.toUpperCase()=='BODY')) {
                if (el.parentNode.scrollTop) {
                    ly -= el.parentNode.scrollTop;
                }
                if (el.parentNode.scrollLeft) {
                    lx -= el.parentNode.scrollLeft;
                }
            }
        } while (el = el.parentNode);
    }
    return {x:lx,y:ly}
}

/***************** Event handling functions ********************************/

function CpAddEvent(elm, evType, fn, useCapture) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
}

function CpRemoveEvent (elm, evType, fn, useCapture) {
    if (elm.removeEventListener) {
        elm.removeEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.detachEvent) {
        var r = elm.detachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = null;
    }
}


/***************** Image and preload functions. ********************************/

function ct_image(img)
	{
	if(!cp2_loaded) {
		return false;
    }

	a=new Image(); 
	a.src=img; 
	return a;
	} 

function ct_swap(docname,swapimage)
	{
	if(!cp2_loaded)
		return;
	document[docname].src = swapimage.src ;
	}

/***************** Functions used by article elements ********************************/

/**
 *  Function used to print flash and movies inline
 *
 *  Done this way to avoid the EOLAS patent
 *
 */
function cpWriteActiveX(activeXstring){
    document.write(activeXstring);
}

/**
 *  Function used to print flash and movies inline
 *
 *  *) These settings might not work in all browser plugins
 *
 *  @src         string The full URL to the video
 *  @sessionName string The session name where users sessionid is stored (used for IE)
 *  @width       int The width
 *  @height      int The height
 *  @mimetype    string The files mimetype
 *  @loop        boolean Whether or not to loop the video *
 *  @autoplay    boolean Whether or not to start the video when it's loaded *
 *  @controller  boolean Whether or not to include plugin controllers *
 */
function cpWriteMediaObject(src, sessionName, width, height, mimeType, loop, autoplay, controller, objId){
    // Get video data
    // IE: We need to add sessionid to the URL in order for the video plugin to use the same session
    //     as IE. If sessionid is not sent, the video plugin will try to load the URL without a valid 
    //     session causing the session to be destroyed.
    if (cpNavigatorUserAgentInfo.isIE){
        var sep = (src.indexOf('?') > -1?'&':'?');
        var sessionID = cpReadCookie(sessionName);
        if (sessionID != null && sessionID.length > 0){
            var src = src +sep +sessionName +'=' +sessionID;
        }
    }
    
    // Detect protocol for codebase
    var codebaseProtocol = (src.substr(0,5)=='https'?'https':'http');
    
    // Handling IE specialties
    var rewriteMimeType = new Object();
    if (cpNavigatorUserAgentInfo.isIE){
        rewriteMimeType['audio/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/x-msvideo'] = 'video/x-ms-wmv';
    }
    // In some cases we must change the mimetype for IE :/
    if (rewriteMimeType[mimeType] != null){
        mimeType = rewriteMimeType[mimeType];
    }
    
    var objectSettings = '';
    if (mimeType != 'application/x-shockwave-flash'){
        objectSettings += '<param name="loop" value="' +(loop?'true':'false') +'" />';
        objectSettings += '<param name="autostart" value="' +(autoplay?'true':'false') +'" />';
        objectSettings += '<param name="controller" value="' +(controller?'true':'false') +'" />';
    } else {
        objectSettings += '<param name="wmode" value="opaque" />';
    }

	// Build object tag and content
    var objectString = '';
    var objectStringStart = '<object type="' +mimeType +'" data="' +src +'" width="' +width +'" height="' +height +'">';
    var objectStringName = '<param name="movie" value="' +src +'" />';
    var objectStringFallback = '<p>(No plugin detected for your OS/browser)</p>';
    var objectStringEnd = '</object>';
    switch (mimeType) {
        case 'application/x-shockwave-flash':
            if (cpNavigatorUserAgentInfo.isIE){
                var objectStringStart = '<object codebase="'+codebaseProtocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' +width +'" height="' +height +'">';
            }
            break;
        case 'application/x-mplayer2':
        case 'video/x-ms-wmv':
        case 'video/x-msvideo':
    		// WMV, MPEG
            objectStringName = '<param name="src" value="' +src +'" />';
    		break;
    		
    	case 'video/quicktime':
    	    // Quicktime in IE
    	    if (cpNavigatorUserAgentInfo.isIE){
    	        objectStringStart = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="'+codebaseProtocol+'://www.apple.com/qtactivex/qtplugin.cab" width="' +width +'" height="' +height +'">';
                objectStringName  = '<param name="src" value="' +src +'" />';
                break;
    	    }
    	    break;
    	
    	case 'video/x-ms-asf':
    	    // ASF in IE
    	    if (cpNavigatorUserAgentInfo.isIE){
                objectStringName = '<param name="FileName" value="' +src +'" />';
                break;
    	    }
    	    break;
    	        
    	default:
    		break;
    }
    
    objectString += objectStringStart;
    objectString += objectStringName;
    objectString += objectSettings;
    objectString += objectStringFallback;
    objectString += objectStringEnd;
    
    try {
        document.getElementById(objId).innerHTML = objectString;
    } catch(e){
        document.write(objectString);
    }
}

/*
  	slideshow function, used to navigate back and forward 
	in a slideshow element.
*/
function slideshow(thearray,imgname,pos,what,theform){
	if(!cp2_loaded)
		return;

	i=eval("slidepos"+pos);
	count=eval("count"+pos);
	
	// Show next picture
	if(what=="next" && thearray[i+1])
		{
		// Load image before we display it, then swap
		temp = ct_image(thearray[i+1]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"++"); // increase counter
		theform.slidetext.value = (i+2)+ " av "+ count; // Set status text
		}
	
	// Show previous picture
	if(what=="previous" && i>0 && thearray[i-1])
		{
		temp = ct_image(thearray[i-1]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"--");
		theform.slidetext.value = (i)+ " av "+ count;
		}
	}

/*
	Function to display keywords in a litle popup box.
*/
function cp2_keywords(keyword_id) {
	cp2_keywordlayer.moveTo(x,y);
	cp2_keywordlayer.setSource("keywords_popup.php?id="+keyword_id,160,160);
	cp2_keywordlayer.show();
}

function cp2_keywords_hide() {
	if(!cp2_loaded)
	   return;

	try {
		if(cp2_keywordlayer.isVisible()) {
			cp2_keywordlayer.hide();
		}
	} catch (e) {
		// no-op
	}
}


/***************** Tile system functions. ********************************/

var cplibTileLoaderXMLHttpObjectArray = new Array();

if (typeof htmlroot != "undefined") {
    var cplibXmlHttpUrl = htmlroot + "xmlhttprequest.php";
} else {
    // htmlroot not available, assuming root  
    var cplibXmlHttpUrl = "/xmlhttprequest.php"; 
}


function cplibRenderAjaxTile (categoryTemplateId, categorytemplateTileId, placeholdername, categoryId, articleId,  callbackFunction) {

    cplibTileLoaderXMLHttpObjectArray[categorytemplateTileId] = new CtXMLHttpRequest();
    var xmlHttp = cplibTileLoaderXMLHttpObjectArray[categorytemplateTileId]; 

    // create the xmlhttprequest object
    
    xmlHttp.SetOnreadystatechange(
        function () {
            if (xmlHttp.getReadyState() == 4) { 
	            try {
	                document.getElementById("cplibajaxtilecontainer-" + categorytemplateTileId + "-loading").style.display ="none";
	                document.getElementById("cplibajaxtilecontainer-" + categorytemplateTileId).style.display ="block";
	                document.getElementById("cplibajaxtilecontainer-" + categorytemplateTileId).innerHTML = xmlHttp.getResponseText();
	                
	                // call the callback function 
	                if (typeof callbackFunction != "undefined" && callbackFunction != null) { 
	                   callbackFunction.call(categorytemplateTileId, placeholdername);
	                }
	                
	            } catch (e) {
	                // alert("noe gikk galt:" + e);
	            
	            }
            }
        
         });
    
    var parameters = new Object();
    parameters['categorytemplatetileID']    = categorytemplateTileId;
    parameters['categorytemplateID']        = categoryTemplateId;
    parameters['categoryID']                = categoryId;
    parameters['articleID']                 = articleId;
    parameters['placeholdername']           = placeholdername;
    
    // Add all existing get parameters so that tiles expecting get parameters are still working
    // get all url parameters into a key=>value array
    if (location.search.length > 0) {
	    var tmp = location.search.substring(1).split("&");
	    for (var key=0; key < tmp.length; key++) { // var key in tmp) {
	        var split = tmp[key].split("=");
	        parameters[split[0]] = split[1];
	    }
     }
    
    xmlHttp.openCorePublishService(cplibXmlHttpUrl ,'categorytemplate.renderajaxtile' , 'html', parameters );


}





