// xml document
var browserConfigDoc;

//browser name 
var browserName = '';

//browser version
var fullVersion;

//browser flash version
var flashVersion = 0.0;

//operating system name
var osName = null;

//object holds how ghost is dealing with this browser
var myBrowserTag = null;

//type:boolean. if the browser enabling popup or not
var popupBlocked = null;

//boolean, check if cookies are enabled or not
var cookieEnabled = null;

//boolean, check if the browser is supported or not
var browserSupported = null;

//boolean, if ghost supports current version
var flashSupported = null;

//boolean, check if flash is installed
var flashInstalled = null;

//latest supported flash
var latestSupportedFlash = null;

//min flash version that is supported by Ghost
var minSupportedFlash = null;

//is Ghost supporting this browser on the current operating system
var osSupported = null;

//language.xml document that's retrieved to be filled in the language combobox
var langDoc;

//ghost user name that's set from the URL
var ghost_userName = null;

//where the current browser recommeded to use or not
var recommendedBrowser = null;

//URL parameter's values
var pValues = new Array();

//URL parameter's names
var pNames = new Array();


// This snippit of code needs common.js
//if the language is specified in the url we should not do a redirect
if(window.location.search.indexOf("language") < 0){
	// if the language is not specified in the url we try to get the language cookie
	var langCookie = getLangCookie();
	// if the language cookie is null then the default language is English
	if(langCookie == null){
		try{
			langCookie = defaultLanguage;
		}catch(e){
			langCookie = "en";
		}
	}
	// if the language cookie is English which is the default we should not do a redirect
	if (langCookie != "en") {
		// if the language cookie is not English, we should do a redirect by appending "language=LANG" to the query parameters and be careful not to loose any previous query params
		if (window.location.search != "") {
			window.location.search += ("&language="+langCookie);
		} else {
			window.location.search += ("?language="+langCookie);
		}
	}
}

function setComboboxLanguage(){
	var lng = getParamValue("language");
	lng = decodeURIComponent(lng);
	if(!lng)return;
	var cmbo = document.getElementById("lanuagesCombobox");
	for(var i=0; i<cmbo.options.length; i++){
		if(lng.toLowerCase().indexOf(cmbo.options[i].value.toLowerCase()) >= 0){
			cmbo.options[i].selected = true;
		}
	}
}

function initBrowserInfo(){
	browserName = getBrowserName().toLowerCase();
	fullVersion = parseInt(getBrowserVersion());
	flashVersion = FlashDetect.major;
	getBrowserConfigDoc();
}
/**
 * to load xml doc
 * @param {} docURL
 * @return {}
 */
function loadHomePageXmlDoc(xmlString) {
	var xmlDoc;
	if (window.ActiveXObject) {
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(xmlString);
			return xmlDoc;
		} else if (document.implementation && document.implementation.createDocument) {
			//for Mozila
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xmlString,"text/xml");
			return xmlDoc;
		}
	return xmlDoc;
}

/**
 * load homePageConfig.xml document
 * @return {}
 */
function getBrowserConfigDoc(){
	//VCURL must be used to avoid cross-domin error
	if(!browserConfigDoc){
		browserConfigDoc = loadHomePageXmlDoc(browserConfig);	
	}
	return browserConfigDoc;
}

/**
 * load my brwoser info tag from the homePageConfig.xml document
 */
function getMyBrowserTag(){
	if(!myBrowserTag){
		var browsersArray = getBrowserConfigDoc().getElementsByTagName("browser");
		for (var i = 0; i < browsersArray.length; i++) {
			if (browsersArray[i].getAttribute("name").toLowerCase() == browserName) {
				if (browsersArray[i].getAttribute("version") == fullVersion) {
					myBrowserTag = browsersArray[i];
				}
			}
		}
		
	}
	return myBrowserTag;
}

/**
 * set if the browser supported or not
 * @return {}
 */
function isSupportedBrowser() {
	if(!browserSupported){
		if(!getMyBrowserTag()){
			browserSupported = false;
		}else{
			browserSupported = getMyBrowserTag().getAttribute("isSupported");
		}
	}
	return browserSupported;
}

/**
 * if the brwoser supports current flash version number
 */
function isSupportedFlash(){
	if(!flashSupported){
		var flashVersionNumber = new Number(flashVersion);
		var minSupprtedVersion = new Number(getMinSupportedFlash());
		flashSupported = (flashVersionNumber >= minSupprtedVersion);
	}
	return flashSupported;
}

/**
 * @return the latest flash version that supported by the browser
 */
function getLatestSupportedFlash() {
	if(!latestSupportedFlash){
		var supportedFalshes = getMyBrowserTag().getElementsByTagName("supportedFlashes")[0];
		var numberOfSupportedFlashes = supportedFalshes.getElementsByTagName("flashVersion");
		var textObject = numberOfSupportedFlashes[numberOfSupportedFlashes.length- 1];
		var textNumber = getTextTagContent(textObject);
		latestSupportedFlash = new Number(textNumber);
	}
	return latestSupportedFlash;
}

/**
 * return the min suppported flash
 */
function getMinSupportedFlash(){
	if(!minSupportedFlash){
		var supportedFalshes = getMyBrowserTag().getElementsByTagName("supportedFlashes")[0];
		var numberOfSupportedFlashes = supportedFalshes.getElementsByTagName("flashVersion");
		var textObject = numberOfSupportedFlashes[0];
		var textNumber = getTextTagContent(textObject);
		minSupportedFlash = new Number(textNumber);
	}
	return minSupportedFlash;
}

/**
 * 
 */
function isFlashInstalled(){
	return FlashDetect.installed;
}

/**
 * 
 */
function isSupportedOS(){
	if(!osSupported){
		var supportedOsBrowser = getMyBrowserTag().getAttribute("isSupported");
		if(supportedOsBrowser == "true"){
			var osTag = getOSChildTag(getMyBrowserTag().getElementsByTagName("OS")[0]);
			osSupported = osTag ? osTag.getAttribute("isBlocked"): false;
		}else{
			osSupported = false;
		}
	}
	return osSupported;
}

/**
 * do for public using
 * get the child tag of OS tag
 * @param {} osTag
 */
function getOSChildTag(osTag){
	var osTagChildren = osTag.getElementsByTagName("os");
	for(var j=0; j<osTagChildren.length; j++){
		if(osTagChildren[j].getAttribute("name").toLowerCase() == getOSName().toLocaleString().toLowerCase()){
			return osTagChildren[j];
		}
	}
	return null;
}

/**
 * set os name
 */
function getOSName() {
	if(!osName){
		var usrAgnet = navigator.userAgent.toLowerCase();
		if (usrAgnet.indexOf("windows") >= 0) {
			osName = "windows";
		} else if (usrAgnet.indexOf("linux") >= 0) {
			osName = "linux";
		} else if (usrAgnet.indexOf("mac") >= 0) {
			osName = "mac";
		}
		return osName
	}
	return osName
}

/**
 * @param instName: the tag name of the instruction in the homePageConfig.xml
 * @return the instruction based on instName
 */

function getInstruction(instName) {
	var instObj = getMyBrowserTag().getElementsByTagName("instructions")[0].getElementsByTagName(instName)[0];
	return getTextTagContent(instObj);
}

/**
 * check if recommended brwoser
 */
function isRecommededBrowser(){
	if(!recommendedBrowser){
		var recommdedTags = getBrowserConfigDoc().getElementsByTagName("recommendedBrwosers")[0].getElementsByTagName("recommdedBrowser");
		for(var i=0; i<recommdedTags.length; i++){
			if(recommdedTags[i].getAttribute("version") == fullVersion){
				recommendedBrowser = true;
				break;
			}
		}
	}
	return recommendedBrowser;
}

/**
 * 
 * @return {}
 */
function isCookieEnabled(){
	if(!cookieEnabled){
		cookieEnabled = (navigator.cookieEnabled) ? true : false;
		try{
			if(browserName.toLowerCase().indexOf("safari") >=0){
				cookieEnabled = navigator.cookieEnabled;
			}else{
				document.cookie = "testcookie@ghost";
				cookieEnabled = (document.cookie.indexOf("testcookie@ghost") != -1 ? true : false);
				
			}
		}catch(e){
			if (typeof navigator.cookieEnabled == "undefined") {
					document.cookie = "testcookie@ghost"
					cookieEnabled = (document.cookie.indexOf("testcookie@ghost") == -1 ? true : false);
			}else{
				cookieEnabled = false;
			}
		}
	}
	return cookieEnabled;
}

/**
 * to check if the browser is blocked popup
 * 
 * @return
 */
function isBlockedPopUp() {
	if (!popupBlocked ) {
		try {
			var mine = window.open('', '',
					'width=0,height=0,left=0,top=0,scrollbars=no');
			mine.close()
			popupBlocked = false;// convert netstate value from null to true
		} catch (err) {
			popupBlocked = true;// convert netstate value from null to false
		}
	}  
	return popupBlocked;
}

/**
 * returns scressn size
 */
function getScreenMaxSize() {
	var xMax;
	var yMax;

	if (typeof(screen.availWidth) == 'number') {
		xMax = screen.availWidth;
		yMax = screen.availHeight;
	} else if (typeof(screen.width) == 'number') {
		xMax = screen.width;
		yMax = screen.height;
	} else if (typeof(window.outerWidth) == 'number') {
		xMax = window.outerWidth;
		yMax = window.outerHeight;
	} else if (document.documentElement
			&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		xMax = document.documentElement.clientWidth;
		yMax = document.documentElement.clientHeight;
	} else if (document.body
			&& (document.body.clientWidth || document.body.clientHeight)) {
		xMax = document.body.clientWidth;
		yMax = document.body.clientHeight;
	} else {
		xMax = 640;
		yMax = 480;
	}
	var isMac = (navigator.appVersion.indexOf("Mac") != -1) ? true : false;
	if (isMac)
		yMax = yMax - 20;

	return "minimizable=no, width="
			+ xMax
			+ ", height="
			+ yMax
			+ ", resizable=no,"
			+ " fullscreen=yes, titlebar=no, directories=no, channelmode=no, scrollbars=no,"
			+ " status=no, toolbar=no, menubar=no, location=no";

}

/**
 * load the language document from language.xml
 */
function getLangDoc(){
	if (!langDoc) {
		langDoc = loadHomePageXmlDoc(languageConfig);
	}
	return langDoc;
}

/**
 * redirect home page with the selected language
 * @param {} combobox
 */
function onChangeLanguage(combobox) {
	addNewLanguageCookie(combobox.value);
	var query = "";
	for (var i = 0; i < pValues.length; i++) {
		if (pNames[i].indexOf("language") >=0) {
			query += (pNames[i] + "=" + combobox.value.toLowerCase());
		} else {
			query += (pNames[i] + "=" + pValues[i]);
		}
		query += "&";
	}
	query = query.substring(0, query.length - 1);
	var docLoc = document.location+"";
	var _baseURL="";
	if(docLoc.indexOf("?")>=0){
		_baseURL = docLoc.split("?")[0];
	}else{
		_baseURL = docLoc;
	}
	window.location = _baseURL + "?" + query;
}

/**
 * extract url params and fill them in pNames and pValues arrays
 */
function extractURLQueries(){
	var loc = document.location + "";
	var attrs = loc.split("?")[1];
	if (attrs && pNames.length == 0 && pValues.length == 0) {
		var nms = attrs.split("&");
		for (var i = 0; i < nms.length; i++) {
			if(nms[i].indexOf("=") <0){
				ghost_userName = nms[i];
				continue;
			}
			pNames.push(nms[i].split("=")[0]);
			pValues.push(nms[i].split("=")[1]);
		}
	}
}

/**
 * return the value of a url parameter based on parameter name
 * @param {} paramName
 */
function getParamValue(paramName){
	extractURLQueries();
	for (var i = 0; i < pNames.length; i++) {
		if (pNames[i] == paramName) {
			return pValues[i];
		}
	}
	return null;
}


//*** open any URL from this function ****************
function  goToUrl(url){	
	var queruStr = document.location.search.substring(1);	
	//open the url's in addtion to the language value if it exist
	if(queruStr.search(/language=/i) != -1)
	{
	//open method with the language value
	window.open (url + "?" + queruStr,"_self");
	return true;
	}else
	{
	//open method without the language value because its not exist
	window.open (url ,"_self");	
	return false;
	}
}

/**
 * dummy function to test if there is blocked plugin
 */
function testBlockedPlugins(){
	
}

function doDirectLogin(){
	extractURLQueries();
	if(ghost_userName){
		
	}
}


/**
 * @return the text text of the passed tag
 */
function getTextTagContent(htmlTag) {
	return (htmlTag.textContent || htmlTag.innerText || htmlTag.text);
}
