/* (c) 2006-7 Ghost(TM) Inc. (http://G.ho.st/home) . All rights reserved.
G.ho.st licenses this software to you under the terms of the 
Common Public License Version 1.0 http://www.opensource.org/licenses/cpl.php 
*/

/**====================================================================================== **
/*  File: common.js    				    		                                          **
/*  Creator: Rami khalyleh                                                                **
/*  Create date: 2007-06-11                                                               **
/*  Authors: Rami khalyleh,...                                                            **
/*                                                                                        **
/**====================================================================================== */
// Global variables
var browserName = getBrowserName();
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isChrome = navigator.userAgent.indexOf('Chrome') != -1;
var isSafari = !isChrome && (navigator.appVersion.indexOf('Safari') != -1);
var isAOL = navigator.appVersion.indexOf("AOL") != -1;
var version = getBrowserVersion();
var isFirefox =  navigator.userAgent.indexOf("Firefox") !=-1 ? true : false ;

//set cookie domain to parent domain
var cookieDomain;


// Write vbscript detection on ie win. IE on Windows doesn't support regular
// JavaScript plugins array detection.
if(isIE && isWin && !isAOL){
  document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
  document.write('On Error Resume Next \n');
  document.write('x = null \n');
  document.write('MM_FlashControlVersion = 0 \n');
  document.write('var VBFlashVer \n');
  document.write('For i = 9 To 1 Step -1 \n');
  document.write('	Set x = CreateObject("ShockwaveFlash.ShockwaveFlash." & i) \n');
  document.write('	MM_FlashControlInstalled = IsObject(x) \n');
  document.write('	If MM_FlashControlInstalled Then \n');
  document.write('		MM_FlashControlVersion = CStr(i) \n');
  document.write('		Exit For \n');
  document.write('	End If \n');
  document.write('Next \n');
  document.write('VBFlashVer = x.GetVariable("$version")\n');
  document.write('Sub app_FSCommand(ByVal command, ByVal args)\n');
  document.write('    call app_DoFSCommand(command, args)\n');
  document.write('end sub\n');
  document.write('<\/SCR' + 'IPT\> \n'); // break up end tag so it doesn't end our script
}

/* This method responsible to get the browser name and flash version and then pass them to canvas*/
function getBrowserAndFlashVerion(){
	var browser = getBrowserName();
	var flashVersion = detectFlash();
	var browserVersion = getBrowserVersion();
	callLaszloMethod("setBrowserAndFlashVerion", new Array(browser, flashVersion, browserVersion), true);
}

/* Browser name method */
function getBrowserName(){
	var nVer = navigator.appVersion;
	var nAgt = navigator.userAgent;
	var browserName  = '';
	var fullVersion  = 0; 
	var majorVersion = 0;
		
	// In Internet Explorer, the true version is after "MSIE" in userAgent
	if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
		browserName  = "IE";
		fullVersion  = parseFloat(nAgt.substring(verOffset+5));
		majorVersion = parseInt(''+fullVersion);
	}
		
	// In Opera, the true version is after "Opera" 
	else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
		browserName  = "Chrome";
		fullVersion  = parseFloat(nAgt.substring(verOffset+6)); // Have not tested this for Chrome
		majorVersion = parseInt(''+fullVersion);
	}
		
	// In Opera, the true version is after "Opera" 
	else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
		browserName  = "Opera";
		fullVersion  = parseFloat(nAgt.substring(verOffset+6));
		majorVersion = parseInt(''+fullVersion);
	}
		
	// In most other browsers, "name/version" is at the end of userAgent 
	else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) 
	{
		browserName  = nAgt.substring(nameOffset,verOffset);
		fullVersion  = parseFloat(nAgt.substring(verOffset+1));
		if (!isNaN(fullVersion)) majorVersion = parseInt(''+fullVersion);
		else {fullVersion  = 0; majorVersion = 0;}
	}
		
	// Finally, if no name and/or no version detected from userAgent...
	if ( browserName.toLowerCase() == browserName.toUpperCase()
		 || fullVersion==0 || majorVersion == 0 ){
		 browserName  = navigator.appName;
		 fullVersion  = parseFloat(nVer);
		 majorVersion = parseInt(nVer);
	}
	
	if(navigator.userAgent.toLowerCase().indexOf("firefox") >= 0){
		browserName = "Firefox";
		var splitArray = navigator.userAgent.toLowerCase().split("firefox");
		fullVersion = splitArray[1].split("/")[1].split(" ")[0];
		majorVersion = parseInt(''+fullVersion);
	}

	return browserName;
}
/* Browser version method */
function getBrowserVersion(){
	var nVer = navigator.appVersion;
	var nAgt = navigator.userAgent;
	var browserName  = '';
	var fullVersion  = 0; 
	var majorVersion = 0;
		
	// In Internet Explorer, the true version is after "MSIE" in userAgent
	if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
		browserName  = "IE";
		//fullVersion  = parseFloat(nAgt.substring(verOffset+5)); // this will not return the value after the ". " if that value was 0
		fullVersion  = nAgt.substring(verOffset+5).split(";")[0];
		majorVersion = parseInt(''+fullVersion);
		
	}
	// In Chrome
	else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
		browserName  = "Chrome";
		fullVersion  = nAgt.substring(verOffset).split("/")[1].split(" ")[0]; // Tested for chrome
		majorVersion = parseInt(''+fullVersion);
	}
	
	// In Opera, the true version is after "Opera" 
	else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
		browserName  = "Opera";
		fullVersion  = parseFloat(nAgt.substring(verOffset+6));
		majorVersion = parseInt(''+fullVersion);
	}
		
	// In most other browsers, "name/version" is at the end of userAgent 
	else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) 
	{
		browserName  = nAgt.substring(nameOffset,verOffset);
		fullVersion  = parseFloat(nAgt.substring(verOffset+1));
		if (!isNaN(fullVersion)) majorVersion = parseInt(''+fullVersion);
		else {fullVersion  = 0; majorVersion = 0;}
	}
		
	// Finally, if no name and/or no version detected from userAgent...
	if ( browserName.toLowerCase() == browserName.toUpperCase()
		 || fullVersion==0 || majorVersion == 0 ){
		 browserName  = navigator.appName;
		 fullVersion  = parseFloat(nVer);
		 majorVersion = parseInt(nVer);
	}
	
	if(navigator.userAgent.toLowerCase().indexOf("firefox") >= 0){
		browserName = "Firefox";
		var splitArray = navigator.userAgent.toLowerCase().split("firefox");
		fullVersion = splitArray[1].split("/")[1].split(" ")[0];
		majorVersion = parseInt(''+fullVersion);
	}

	return fullVersion;
}

function detectFlash() {  
    var actualVersion = 0;
    if (navigator.plugins && 
        (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) ) {

        // Some version of Flash was found. Time to figure out which.
        // Set convenient references to flash 2 and the plugin description.
        var isVersion2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
        var flashDescription = navigator.plugins["Shockwave Flash" + isVersion2].description;

        var flashVersion = parseInt(flashDescription.substring(16));
        var minorVersion = flashDescription.substring(flashDescription.indexOf('r') + 1);
    } else if (! isIE) {
        var flashVersion = 0;
        var minorVersion = 0;
    } else {
        var vbver =  eval('VBFlashVer');
        if (vbver) {
            vbver = vbver.substring(vbver.indexOf(' ') + 1).split(',');
            var flashVersion = vbver[0];
            var minorVersion = vbver[2];
        } 
    }
  
    actualVersion = parseFloat(flashVersion + '.' + minorVersion)

    // If we're on msntv (formerly webtv), the version supported is 4 (as of
    // January 1, 2004). Note that we don't bother sniffing varieties
    // of msntv. You could if you were sadistic...
    if (navigator.userAgent.indexOf("WebTV") != -1) actualVersion = 4;  

    return actualVersion;
}

function doLaunchApp(AppName, arg1, arg2){
	callLaszloMethod("doLaunchAppFromWizard", new Array(AppName, arg1, arg2), true);
}

function getOSName() {
	var usrAgnet = navigator.userAgent.toLowerCase();
	if (usrAgnet.indexOf("windows") >= 0) {
		return "windows"
	} else if (usrAgnet.indexOf("linux") >= 0) {
		return "linux";
	} else if (usrAgnet.indexOf("mac") >= 0) {
		return "mac";
	}
}

/**
 * 
 * @return {}
 */
function getDomainName(){
	if(!cookieDomain){
		var host = window.location.host+"";
		var serverNameDotArray = host.split(":")[0].split(".");
		if (serverNameDotArray.length > 2) {
		   if ((serverNameDotArray[serverNameDotArray.length - 2].length > 2) && (serverNameDotArray[serverNameDotArray.length - 1].length > 2)) {
		    cookieDomain = "." + serverNameDotArray[serverNameDotArray.length - 2] + "." + serverNameDotArray[serverNameDotArray.length - 1];
		   }
	   else {
	    		cookieDomain = "." + serverNameDotArray[serverNameDotArray.length - 3] + "." + serverNameDotArray[serverNameDotArray.length - 2] + "."
	      			+ serverNameDotArray[serverNameDotArray.length - 1];
	   		}
		}
	}
	return cookieDomain;
}

function doOpenNewWindow(url){
	openNewWindow(url);
}

/* opens a focused popup window */
function openNewWindow(src, attrs) {
	if (attrs) {
		attrs = 'top=0,left=0,scrollbars=yes,resizable=yes,'+attrs;
	} else {
		var attrs = 'top=0,left=0,scrollbars=yes,resizable=yes';
	}
	var newWindow = window.open(src,'_blank',attrs);
	if (window.focus){
		newWindow.focus();
	} 
	
}

function addCookie(cookieName, cookieValue, expInMills , cookiePath, cookieDomain) {
  var cookie = cookieName + "=" + cookieValue;
  if (expInMills) {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime() + expInMills);
    cookie += "; expires=" + expireDate.toGMTString();
  }
  if (cookiePath){
        cookie += "; path=" + cookiePath;
  }
  if (cookieDomain) {
        cookie += "; domain=" + cookieDomain;
  }
  else{
  	
  	var domainName = getDomainName();
  	if(domainName != "null" && domainName != null){
  	cookie += "; domain=" + domainName;
  	}
  }
  document.cookie = cookie;
}

function addNewLanguageCookie(lang){
	var currentDate=new Date();
	var cookieName="ghostcookieWSLanguage";
	var str='<ghostCookie><type>ghostcookieWSLanguage</type><language>'+lang+'</language><time>'+currentDate+'</time></ghostCookie>';
	addCookie(cookieName,str,1000000000000, "/");
}

/**
 * delete the cookie with the passed name from the cookies
 */
function deleteCookie (cookieName) {
  var expireDate = new Date();
  expireDate.setTime (expireDate.getTime()-1);
  document.cookie = cookieName += "=; expires=" + expireDate.toGMTString();
}


/**
 * return the cookie value as a string if the cookie name was found
 */
function getCookie (cookieName) {
  var cookie = document.cookie.match ('(^|;) ?' + cookieName + '=([^;]*)(;|$)');
  if (cookie){
    return ( unescape ( cookie[2] ) );
  } else {
    return null;
  }
}

function getAllCookies(){
	var cookies = document.cookie;
		return( cookies);
}

function getRememberCookies(){
	var cookiesArrays= document.cookie.split(';')
	var allCookies ="null";
	for(var i=0;i<cookiesArrays.length;i++){
		if(cookiesArrays[i].indexOf("ghostcookieRemember") != -1){
			if(allCookies == "null"){
				allCookies = cookiesArrays[i]+";";
			}
			else{
				allCookies = allCookies +cookiesArrays[i]+";";
			}
			
  
		}
		else if(cookiesArrays[i].indexOf("ghostcookieWSLanguage") != -1){
			if(allCookies == "null"){
				allCookies = cookiesArrays[i]+";";
			}
			else{
				allCookies = allCookies +cookiesArrays[i]+";";
			}
		
		}
	}
	if(allCookies  != "null"){
		var result=escape(allCookies);
		if (isSafari) {
			setTimeout('lz.embed.callMethod(\'canvas.getUsersCookies(\''+result+'\')\')', 2000);
		} else {
			lz.embed.callMethod('canvas.getUsersCookies(\''+result+'\')')
		}
	}
	
}

/**
 *return the language from the cookie
 */
function getLangCookie(){
	var lang = getCookie("ghostcookieWSLanguage");
	if(lang != null && lang != "null"){
		lang = lang.split("<language>")[1];
		lang = lang.split("</language>")[0];
		return lang.toLowerCase();
	}
	return null;
}

/**
 * the lower code is the modification to detectFlash() method
 */
var FlashDetect = new function(){
    var self = this;
    self.installed = false;
    self.raw = "";
    self.major = -1;
    self.minor = -1;
    self.revision = -1;
    self.revisionStr = "";
    var activeXDetectRules = [
        {
            "name":"ShockwaveFlash.ShockwaveFlash.7",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash.6",
            "version":function(obj){
                var version = "6,0,21";
                try{
                    obj.AllowScriptAccess = "always";
                    version = getActiveXVersion(obj);
                }catch(err){}
                return version;
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        }
    ];
    /**
     * Extract the ActiveX version of the plugin.
     * 
     * @param {Object} The flash ActiveX object.
     * @type String
     */
    var getActiveXVersion = function(activeXObj){
        var version = -1;
        try{
            version = activeXObj.GetVariable("$version");
        }catch(err){}
        return version;
    };
    /**
     * Try and retrieve an ActiveX object having a specified name.
     * 
     * @param {String} name The ActiveX object name lookup.
     * @return One of ActiveX object or a simple object having an attribute of activeXError with a value of true.
     * @type Object
     */
    var getActiveXObject = function(name){
        var obj = -1;
        try{
            obj = new ActiveXObject(name);
        }catch(err){
            obj = {activeXError:true};
        }
        return obj;
    };
    /**
     * Parse an ActiveX $version string into an object.
     * 
     * @param {String} str The ActiveX Object GetVariable($version) return value. 
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseActiveXVersion = function(str){
        var versionArray = str.split(",");//replace with regex
        return {
            "raw":str,
            "major":parseInt(versionArray[0].split(" ")[1], 10),
            "minor":parseInt(versionArray[1], 10),
            "revision":parseInt(versionArray[2], 10),
            "revisionStr":versionArray[2]
        };
    };
    /**
     * Parse a standard enabledPlugin.description into an object.
     * 
     * @param {String} str The enabledPlugin.description value.
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseStandardVersion = function(str){
        var descParts = str.split(/ +/);
        var majorMinor = descParts[2].split(/\./);
        var revisionStr = descParts[3];
        return {
            "raw":str,
            "major":parseInt(majorMinor[0], 10),
            "minor":parseInt(majorMinor[1], 10), 
            "revisionStr":revisionStr,
            "revision":parseRevisionStrToInt(revisionStr)
        };
    };
    /**
     * Parse the plugin revision string into an integer.
     * 
     * @param {String} The revision in string format.
     * @type Number
     */
    var parseRevisionStrToInt = function(str){
        return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
    };
    /**
     * Is the major version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required major version.
     * @type Boolean
     */
    self.majorAtLeast = function(version){
        return self.major >= version;
    };
    /**
     * Is the minor version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required minor version.
     * @type Boolean
     */
    self.minorAtLeast = function(version){
        return self.minor >= version;
    };
    /**
     * Is the revision version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required revision version.
     * @type Boolean
     */
    self.revisionAtLeast = function(version){
        return self.revision >= version;
    };
    /**
     * Is the version greater than or equal to a specified major, minor and revision.
     * 
     * @param {Number} major The minimum required major version.
     * @param {Number} (Optional) minor The minimum required minor version.
     * @param {Number} (Optional) revision The minimum required revision version.
     * @type Boolean
     */
    self.versionAtLeast = function(major){
        var properties = [self.major, self.minor, self.revision];
        var len = Math.min(properties.length, arguments.length);
        for(i=0; i<len; i++){
            if(properties[i]>=arguments[i]){
                if(i+1<len && properties[i]==arguments[i]){
                    continue;
                }else{
                    return true;
                }
            }else{
                return false;
            }
        }
    };
    /**
     * Constructor, sets raw, major, minor, revisionStr, revision and installed public properties.
     */
    self.FlashDetect = function(){
        if(navigator.plugins && navigator.plugins.length>0){
            var type = 'application/x-shockwave-flash';
            var mimeTypes = navigator.mimeTypes;
            if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
                var version = mimeTypes[type].enabledPlugin.description;
                var versionObj = parseStandardVersion(version);
                self.raw = versionObj.raw;
                self.major = versionObj.major;
                self.minor = versionObj.minor; 
                self.revisionStr = versionObj.revisionStr;
                self.revision = versionObj.revision;
                self.installed = true;
            }
        }else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
            var version = -1;
            for(var i=0; i<activeXDetectRules.length && version==-1; i++){
                var obj = getActiveXObject(activeXDetectRules[i].name);
                if(!obj.activeXError){
                    self.installed = true;
                    version = activeXDetectRules[i].version(obj);
                    if(version!=-1){
                        var versionObj = parseActiveXVersion(version);
                        self.raw = versionObj.raw;
                        self.major = versionObj.major;
                        self.minor = versionObj.minor; 
                        self.revision = versionObj.revision;
                        self.revisionStr = versionObj.revisionStr;
                    }
                }
            }
        }
    }();
};
FlashDetect.JS_RELEASE = "1.0.4";
