/**
 * @author gskocibusic
 */

var contentLoaded = false;
var tempContent;
var tool;
var siteToLoad = "";
var siteLoaded = "";
var contentLoadedFromAjax = "";
var ajaxFinnished = false;
var afterSiteChange = false;
var sitesVisited = new Array();
var requestedSite = "";

dojo.require("dojo.back");

ApplicationState = function(stateData, toolFunction){
	this.stateData = stateData;
	this.toolFunction = toolFunction;
}

dojo.extend(ApplicationState, {
	back: function(){
		if (this.toolFunction != null && this.stateData == requestedSite) {
			eval(this.toolFunction);
		} else {
			openPage(this.stateData, true, true);
		}
	},
	forward: function(){
		if (this.toolFunction != null && this.stateData == requestedSite) {
			eval(this.toolFunction);
		} else {
			openPage(this.stateData, true, true);
		}
	}
});

function getFlashMovie(movieName) {
	  
   
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
  	} else {

		return document[movieName];
        }	
}

function getWindowInformation(value){
	windowInformation = new Array();
	windowInformation['winWidth'] = document.body.clientWidth;
	if (document.body.clientHeight == 0) {
		windowInformation['winHeight'] = window.innerHeight;
	}
	else {
		windowInformation['winHeight'] = document.body.clientHeight;
	}
	windowInformation['docWidth'] = document.body.scrollWidth;
	windowInformation['docHeight'] = document.body.scrollHeight;
	windowInformation['scrollLeft'] = document.body.scrollLeft;
	windowInformation['scrollTop'] = document.body.scrollTop;
	return windowInformation[value];
}
            
function getDivInformation(objId, attribute){
	divInformation = new Array();
	if (typeof objId != 'object') {
		objId = document.getElementById(objId);
	}
	if (objId) {
		divInformation['offsetLeft'] = objId.offsetLeft;
		divInformation['offsetTop'] = objId.offsetTop;
		divInformation['styleLeft'] = parseInt(objId.style.left);
		divInformation['styleTop'] = parseInt(objId.style.top);
		divInformation['width'] = objId.offsetWidth;
		divInformation['height'] = objId.offsetHeight;
		divInformation['visibility'] = objId.style.visibility;
		divInformation['display'] = objId.style.display;
		divInformation['zIndex'] = objId.style.zIndex;
		return divInformation[attribute];
	}
}

function checkWindowSize(){
	if (getWindowInformation('winWidth') < 1255) {
		if (document.getElementById('flash_bg')) {
			resizeLayer('flash_bg', 1280);
		}
	}
	else {
		if (document.getElementById('flash_bg')) {
			resizeLayer('flash_bg', '100%');
		}
	}
}

            
function resizeLayer(objId, newWidth, newHeight){
	if (typeof objId != 'object') {
		objId = document.getElementById(objId);
	}
	if (objId) {
		currentDiv = objId;
		lastWidth = getDivInformation(objId, 'width');
		lastHeight = getDivInformation(objId, 'height');
		if (newWidth) {
			if (typeof newWidth == 'string') {
				objId.style.width = newWidth;
			}
			else {
				objId.style.width = newWidth + 'px';
			}
		}
		if (newHeight) {
			if (typeof newHeight == 'string') {
				objId.style.height = newHeight;
			}
			else {
				objId.style.height = newHeight + 'px';
			}
		}
	}
}


function changeFonts(){
	if(typeof sIFR == "function"){

		//this is the old syntax - first not done so good. not seen any difference on output
		sIFR.replaceElement("#topPartCareer h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement("#topPartCareer h2", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement("#topPartNewslist h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement("#topPartNewslist h2", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement("#rightTopPartCareer h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement("#middlePartContact h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#041d33", sWmode:"transparent"}));
		sIFR.replaceElement("#bottomPartContact h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#041d33", sWmode:"transparent"}));
		sIFR.replaceElement("#rightTopPartContact h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement("#middlePartEditorial h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#13314b", sWmode:"transparent", nPaddingTop:0, nPaddingBottom:0}));
		sIFR.replaceElement("#middlePartEditorial h2", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtComBold.swf", sColor: "#4a82b6", sWmode:"transparent", nPaddingTop:0, nPaddingBottom:0}));
		sIFR.replaceElement("#editorialExternalLinks h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement("#bottomPartEditorial h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtComBold.swf", sColor: "#13314b", sWmode:"transparent"}));
		sIFR.replaceElement("#tableDiv h2", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#13314b", sWmode:"transparent"}));
		sIFR.replaceElement("#topPartSearch h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#13314b", sWmode:"transparent"}));
		sIFR.replaceElement("#bottomPartSearch h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#13314b", sWmode:"transparent"}));
		sIFR.replaceElement("#topPartSitemap h1", named({sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#FFFFFF", sWmode:"transparent"}));

		//this is the prefered syntax - first not done so good. have not seen any difference on output
		sIFR.replaceElement(named({sSelector:"#editorialTeasers h1", sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor:"#FFFFFF", sWmode:"transparent"}));
		sIFR.replaceElement(named({sSelector:"#topPartGallery h1", sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#13314b", sWmode:"transparent", nPaddingTop:0, nPaddingRight:0, nPaddingBottom:0, nPaddingLeft:0}));
		sIFR.replaceElement(named({sSelector:"#topPartGallery h2", sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtComBold.swf", sColor: "#4a82b6", sWmode:"transparent", nPaddingTop:0, nPaddingRight:0, nPaddingBottom:0, nPaddingLeft:0}));
		sIFR.replaceElement(named({sSelector:"#middlePartGallery h1", sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtCom.swf", sColor: "#13314b", sWmode:"transparent", nPaddingTop:0, nPaddingRight:0, nPaddingBottom:0, nPaddingLeft:0}));
		sIFR.replaceElement(named({sSelector:"#middlePartGallery h2", sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtComOrg.swf", sColor: "#4a82b6", sWmode:"transparent", nPaddingTop:0, nPaddingRight:0, nPaddingBottom:0, nPaddingLeft:0}));
		sIFR.replaceElement(named({sSelector:"#middlePartGallery h3", sFlashSrc:url_prefix+"/_common/swf/tradeGothicLtComOrg.swf", sColor: "#13314b", sWmode:"transparent", nPaddingTop:0, nPaddingRight:0, nPaddingBottom:0, nPaddingLeft:0}));
	};
}

function setSiteLoaded(){
	var temp = self.location.href;
	temp = temp.replace(/\//g,"\\");
	var i = temp.lastIndexOf("\\");
	if (i > -1) {
		siteLoaded = temp.substring(i+1);
	} else {
		siteLoaded = temp;
	}
}

function onloadStatic(){
	dojo.addOnLoad(function(){
		changeFonts();
		checkWindowSize();
		setSiteLoaded();
		var state = new ApplicationState(url_prefix+"/"+siteLoaded);
		dojo.back.setInitialState(state);
		window.onresize = checkWindowSize;
	});
}

function onloadFlash(){
	dojo.addOnLoad(function(){
		checkWindowSize();
		setSiteLoaded();
		var state = new ApplicationState(url_prefix+"/"+siteLoaded);
		dojo.back.setInitialState(state);
		window.onresize = checkWindowSize;
	});
	//maybe something special to do
	//function is called in the part, where the backgroundcontent is set!

	var query = window.top.location.search;
	if (query && query.indexOf("still=true") >= 0) {
		setTimeout("stopBgLoop()", 1000);
	}

}

function stopBgLoop() {
	alert("stopLoop");
	getFlashMovie("bg").stopLoop();
}

function loadFile(site) {
	dojo.xhrGet( { 
		url: site, 
		handleAs: "text",

		timeout: 25000, // Time in milliseconds

		load: function(response, ioArgs) {
			var temp = response;
			var start = temp.indexOf("<!"+"-- regExpTemp:start --"+">") + 25;
			var count = temp.indexOf("<!"+"-- regExpTemp:end --"+">") - start;
			var partInside = temp.substr(start, count);
      ajaxFinnished = true;
			contentLoadedFromAjax = removeAllFlash(partInside);
			if(requestedSite == site){
				dojo.byId("content").innerHTML = contentLoadedFromAjax;
				if(isToolSite(site)) {
					writeToolFlash(site);
				} else {
					writeAllFlash(contentLoadedFromAjax);
				}
				changeFonts();
				finnishSiteChange();
			}
		},
		error: function(response, ioArgs) { 
			console.error("HTTP status code: ", ioArgs.xhr.status); 
			return response; 
		}
	});
}

function isToolSite(url){
	var site = ""+url;
	if (site.indexOf("trades_tool.html")!=-1 || site.indexOf("fleet_tool.html")!=-1 || site.indexOf("people_tool.html")!=-1)
		return true;
	return false;
}

function writeToolFlash(url){
//alert("writeFlash"+url);
	var site = ""+url;
	if (site.indexOf("/trades_tool.html")!=-1) {
		tool= new SWFObject(url_prefix+"/_common/swf/oldendorfftoolpreloader.swf", "trades_tool", "690", "410", "9", "#182547");
		tool.addParam("quality", "high");
		tool.addParam("wmode", "opaque");
		tool.addParam("allowScriptAccess", "always");
		tool.addVariable("configUrl", url_prefix+"/_common/xml/tradeToolConfig.xml");
		tool.addVariable("movieUrl", url_prefix+"/_common/swf/fleet_tool.swf");

		tool.addVariable("startUpScenario", "trades");
		tool.write("flashToolContent");
                init_showTradesCargo("all_init" );
	}
	else if (site.indexOf("/fleet_tool.html")!=-1) {
		tool= new SWFObject(url_prefix+"/_common/swf/oldendorfftoolpreloader.swf", "trades_tool", "690", "410", "9", "#182547");
		tool.addParam("quality", "high");
		tool.addParam("wmode", "opaque");
		tool.addParam("allowScriptAccess", "always");
		tool.addVariable("configUrl", url_prefix+"/_common/xml/tradeToolConfig.xml");
		tool.addVariable("movieUrl", url_prefix+"/_common/swf/fleet_tool.swf");

		tool.addVariable("startUpScenario", "fleet");
		tool.write("flashToolContent");
		if (shipgroup_key != "") {
			showFleet(shipgroup_key);
		} else {
			init_showFleet("all");
		}
	}
	else if (site.indexOf("/people_tool.html")!=-1) {
		tool= new SWFObject(url_prefix+"/_common/swf/oldendorfftoolpreloader.swf", "people", "690", "410", "9", "#182547");
		tool.addParam("quality", "high");
		tool.addParam("wmode", "opaque");
		tool.addParam("allowScriptAccess", "always");
		tool.addVariable("configUrl", url_prefix+"/_common/xml/peopleToolConfig.xml");
		tool.addVariable("movieUrl", url_prefix+"/_common/swf/people_tool.swf");

		tool.addVariable("startUpScenario", "trades");
		tool.write("flashToolContent");
                changeDep(main_office["officefolder"] ,0, false);
	}
}

function fadeOutComplete(){
	//not used at the moment
}


function fadeOutFlash(){
	//not used at the moment
}

function fadeInStartpage() {
	getFlashMovie("swfContent").fadeIn();
	getFlashMovie("nav").fadeIn();
}

function initComplete(){
	if(afterSiteChange){
		getFlashMovie("swfContent").fadeIn();
	}
}

function removeAllFlash(toParse) {

  var result = toParse;
  
  // editorial flash-objects in content
  result = removeFlashPart(result, 'id="flashEditorial');

  // editorial flash-teaser-objects
  result = removeFlashPart(result, 'id="linkExt');
  
  // home and subhome content
  result = removeFlashPart(result, 'id="flash_content"');
 
  return result; 
}

function removeFlashPart(toParse, lookupString) {
	temp = "";
	posStartSearch = 0;
	endStartDiv = 0;
	endHref = 0;
	startCopy = 0;
	endCopy = 0;
	endPos = toParse.length - 1;
		
	//clear embeded flash-objects in content
	j = toParse.indexOf(lookupString);
	while(j > -1) {
		partWithRef = toParse.substring(j, endPos);		//somewhere in flashId
		endStartDiv = partWithRef.indexOf(">");
		temp = temp + toParse.substring(startCopy, j+endStartDiv+1)+"</div>";
		startCopy = toParse.indexOf("</div>", j+endStartDiv);
		startCopy = startCopy+6;
		posStartSearch = j+endStartDiv;
		j = toParse.indexOf(lookupString, posStartSearch);
	}
	
	return temp + toParse.substring(startCopy, endPos+1);
	
}

function writeAllFlash(toParse) {

  // editorial flash-objects in content
  writeFlashPart(toParse, 'id="flashEditorial');

  // editorial flash-teaser-objects
  writeFlashPart(toParse, 'id="linkExt');
  
  // home and subhome content
  writeFlashPart(toParse, 'id="flash_content"');
  
}

function writeFlashPart(toParse, lookupString) {
	posStartSearch = 0;
	endStartDiv = 0;
	endHref = 0;
	startCopy = 0;
	endCopy = 0;
	endPos = toParse.length - 1;
	j = toParse.indexOf(lookupString);
	while(j > -1) {
		startCopy = toParse.indexOf('javascript">', j);
		endCopy = toParse.indexOf('script>', j);
		jsCode = toParse.substring(startCopy+12, endCopy-2);		
		jsCode = jsCode.replace("\n", "");
		jsCode = jsCode.replace("\r", "");
		
		eval(jsCode);
		
		j = toParse.indexOf(lookupString, endCopy);
	}
}


var office_key ="";
var shipgroup_key ="";

function finnishSiteChange(url){
	siteLoaded = url;
	contentLoadedFromAjax = "";
	flashFadeOutComplete = false;
	ajaxFinnished = false;
	if (office_key.indexOf("/people/offices/_")!=-1) {
		var selectKey = office_key;
		office_key ="";
		tool_selectPeople(selectKey );
	} else if (shipgroup_key != "") {
		var selectKey = shipgroup_key;
		shipgroup_key ="";
		init_flashFleet(selectKey);
	}
	afterSiteChange = true;

	window.scrollTo(0, 0);
}

function loadNewSite(url){
	fadeOutComplete = true;
	loadFile(url);
}

function isInternalUrl(url){
	if(url.indexOf("http:") > -1){
		return false;
	}
	if(url.indexOf("https:") > -1){
		return false;
	}
	if(url.indexOf("mailto:") > -1){
		return false;
	}
	if(url.indexOf(".html") > 0) {
		return true;
	}
	if(url.indexOf(".htm") > 0) {
		return true;
	}
	if(url.indexOf(".jsp") > 0) {
		return true;
	}
	if(url.indexOf("/people/offices/") > 0) {
		return true;
	}
	if(url.indexOf("/fleet/shipGroups/") > 0) {
		return true;
	}
	if(url.charAt(url.length - 1) == '/') {
		return true;
	}
	return false;
}


function openPage(url, highlightNav, calledFromDojoHistory){
//alert("op:"+url);
	if(isInternalUrl(url)){
		if(url.indexOf("/blogbook") >= 0) {
			self.location.href=url;
			return;
		}
		if (url.indexOf("/people/offices/_")!=-1) {
			office_key = url;
			url = url_prefix + "/people/people_tool.html"; 
		} else if (url.indexOf("/fleet/shipGroups/")!=-1) {
			shipgroup_key = url.substring(url.indexOf("/fleet/shipGroups/"));
			if (shipgroup_key.charAt(shipgroup_key.length-1) == '/') {
				shipgroup_key = shipgroup_key.substring(0, shipgroup_key.length-1);
			}
			url = url_prefix + "/fleet/fleet_tool.html";
		}
		requestedSite = url;
		flashFadeOutComplete = true;
		loadNewSite(url);
		if(highlightNav)
			selectNode(url);
		if(!calledFromDojoHistory) {
			var newState = new ApplicationState(url);
			dojo.back.addToHistory(newState);
		}


	}
	else {
		window.open(url, "_blank");
	}
}

function selectNode(url){
	if (url.indexOf("/company/news/") >= 0) {
		url = url_prefix + "/company/news.html";
	}
	getFlashMovie("nav").selectNode(url);
}

function toolInitComplete(){		
	getFlashMovie("nav").toolInitComplete();
}

function search(searchFor){
	openPage("/cms/search.jsp?query="+searchFor+"&action=search");
}

function checkSearchByEnter(e) {
  var characterCode = null;
  if(e && e.which) {
    e = e;
    characterCode = e.which;
  } else {
    e = event;
    characterCode = e.keyCode;
  }
  if(characterCode == 13) {
    document.forms[0].submit();
    return false
  } else {
    return true
  }
}

function switchVisibleContent(showId, hideId) {
  var showObj = document.getElementById(showId);
  var hideObj = document.getElementById(hideId);
  if (hideObj) {
    hideObj.style.display = "none";
  }
  if (showObj) {
    showObj.style.display = "block";
  }
}

function playVideoHighligtOn(anImage) {
	var imgSrc = anImage.src;
	imgSrc = imgSrc.substring(0, imgSrc.length - 4) + "-over.png";
	anImage.src = imgSrc;
}
function playVideoHighligtOff(anImage) {
	var imgSrc = anImage.src;
	imgSrc = imgSrc.substring(0, imgSrc.length - 9) + ".png";
	anImage.src = imgSrc;
}

