//global variables first:
var poller=null;
var dialog=null;
var newsAdmin=null;
function getElementById(id){return document.getElementById(id);}
function fsEditorPopup(u){
	var windowAttributes = "scrollbars=1,menubar=0,resizable=1,width=830,height=850"; 
	//alert("URL: " + u + ".");
	dialog = window.open(u,"wcmEditorPopupWindow",windowAttributes);
	if (u.indexOf("FS_CHECK_OUT",0) > -1) {
		poller = new Poller(dialog);
	}
}
function fsNewsadminPopup(u){
	newsAdmin = window.open(u,"newsAdminWindow");
}


function createXMLHttpRequest(){	
	if ( window.ActiveXObject )
		return new ActiveXObject("Microsoft.XMLHTTP");
	else if ( window.XMLHttpRequest )
		return new XMLHttpRequest();
}

function loadUriToRequest( uri, createTimeStamp, request, synchronize ){
	if (createTimeStamp){
		//create timestamp if you want to disable cache.
		var timeStamp = new Date().getTime();
		uri = uri + "&ts=" + timeStamp;
	} 
	var async = true;
	if (synchronize) {
		async = !synchronize;
	}
	request.open("GET", uri, async);
	request.send(null);  
}
function undoCheckout(param){
	if ( !cdfHandler ) return;
	
	if(cdfHandler.getDDocName()=="" || cdfHandler.getDDocName()==undefined) return false;
	var a = createXMLHttpRequest();	
	var u = cdfHandler.getUndoCheckOutUrl();
	loadUriToRequest(u, false, a, false);
}

function deleteItem(dDocName, serviceRoot, dID){

	var a = createXMLHttpRequest();
	var u = serviceRoot+"?IdcService=UPDATE_DOCINFO&IsJson=1&dID="+dID+"&dDocName="+dDocName+"&dInDate=1.1.1970 00:00&dOutDate=2.1.1970 00:00";
	loadUriToRequest(u, false, a, false);
	
	if (typeof jQuery == 'undefined') {  
		setTimeout(function(){
    		window.location.reload();
    	},2000);
	} else {
		$("#row"+dID).fadeTo(2, .3);
	    setTimeout(function(){
			pollReleased(dID, serviceRoot)
		},2000);
	}
}

// Poll content item until it becomes expired. Requires jQuery.
function pollReleased(dID, serviceRoot){
	var releasedPoller = setTimeout(function(){
		$.ajax({
	   		url: serviceRoot+'?IdcService=DOC_INFO&IsJson=1',
	    	cache: false,
	    	dataType: "json",
	    	async: false,
	    	method: "get",
	    	data: ({"dID":dID}),
	    	success: function(data, textStatus, XMLHttpRequest){
	        	//console.log(data);
	        	clearTimeout("releasedPoller");
	        	
	        	if(data.LocalData.dStatus == "EXPIRED"){
	            	$("#row"+data.LocalData.dID).slideUp();
	        	}else{
	            	pollReleased(dID, serviceRoot);
	        	}
	    	},
	    	error: ErrorHandler
		});
	},2000);
}

function ErrorHandler(xml, stat, err){
	var msg = "Odottamaton virhe.\n\nOle ystävällinen ja lähetä tämän ikkunan kuva webmasterille, kiitos.\n\n" + stat+": "+xml.status+" "+xml.statusText+"\n"+xml.responseText+"\n"+xml.getAllResponseHeaders();
	alert(msg);
	console.log(xml);
	console.log(stat);
	console.log(err);
}

function getAddress(pre,suf){
	return pre+"@"+suf;
}
function getLink(pre,suf){
	return "mailto:"+pre+"@"+suf;
}

function childIsClosingHandler(child){
	if(poller!=null){
		poller.setBuryPolled( undoCheckout );
		poller.poll();
	}
}

Poller = function(someThingToPoll){
	var pollingTarget = someThingToPoll;
	var buryPolled = null; //this should be a function. This is invoked when someThingToPoll dies.
	var handle = null;
	var invokeBuryPolled = function(){
		if ( buryPolled ){
			buryPolled();
		}
	}
	var poll = function(){
		if (!pollingTarget || typeof( pollingTarget )=="undefined" || pollingTarget.closed) {
			invokeBuryPolled();
			poller = null;
		} else {
			this.handle = setTimeout("poller.poll()", 500 );
		}
	}
	var stop = function(){
		if ( this.handle ) {
			clearTimeout(this.handle);
		}
	}
	this.stop = stop;
	this.poll = poll;	
	this.setBuryPolled = function(handler){
		buryPolled = handler;
	}
}
/* simple version of Java's Hashtable. All features are not Implemented. Only those which are needed */
Hashtable = function(){
	var values = new Array();
	var keys = new Array();
	
	this.indexOf = function( key ){
		for ( var i=0; i<keys.length; i++){
			if ( keys[i]==key ) return i;
		}
		return -1; //not found
	}
	this.getLength = function(){
		return keys.length;	
	}
	this.put = function(key, value){
		if ( key == null || value == null ) return;
		var index = keys.length; //default value but...
		//one key is accepted only once
		var tmp = this.indexOf( key );
		if ( tmp >= 0 ) index = tmp; //index that should be updated
		//updating existing or new entry:
		keys[index] = key;
		values[index] = value;
	}
	/*
	returns value object that matches the key
	*/
	this.get = function(key){
		var ind = this.indexOf(key);
		if ( ind>=0 )return values[ind];
		return null;		
	}
	/*
	returns value object that matches the key
	*/
	this.getPairValue = function(ind){
		if ( ind<0 || ind>=values.length ) return null;
		var nameStr = keys[ind];
		var valueStr = values[ind];
		var ret = new PairValue( nameStr, valueStr);
		return ret;		
	}
	/**
	returns copy of key array
	*/
	this.getKeys = function(){
		var retValue = new Array();
		for (var i=0;i<keys.length;i++){
			retValue[i] = keys[i];
		}
		return retValue;
	}
	/**
	returns pointer to values array
	*/
	this.getValuesPtr = function(){
		return values;
	}
	/** overriding **/
	this.toString = function(keyValueSeparator, lineFeed){
		if ( !keyValueSeparator ) keyValueSeparator="=";
		if ( !lineFeed ) lineFeed="\n";
		var str = "";
		for ( var i=0;i<keys.length; i++ ){
			if ( str != "") str += lineFeed;
			str += keys[i] + keyValueSeparator + values[i];
		}
		return str;
	}
} //class ends
PairValue = function(n, v){
	var name = n;
	var value = v;
	this.getName = function(){
		return name;
	}
	this.getValue = function(){
		return value;
	}
	this.toJSON = function(){
		return "could be";
	}
	this.toString = function(){
		var str = "";
		str += this.getName() + "=" + this.getValue();
		return str;
	}
}

//luokka jolla voi luoda cdf tiedoston
CDFController = function(parServiceRoot){
	// Null the poller
	poller=null;
	
	//ATTRIBUTES
	var serviceRoot = parServiceRoot;	
	var infoBinder = null; //alustetaan luonnin callbackissa. This knows dDocName.
	var idcServiceName = "FS_GET_FORM";
	var dDocName = "";
		var origAccount = "";
	var origInDate =  "";
	var dID = "";
	//metadata fields are in hashtable
	var fieldsAndValues = new Hashtable(); //contains field names and values
	var placeHolderName = "";
		
	//METHODS
	this.appendFieldsAndValues = function(fieldName, valueStr){
		if ( fieldsAndValues==null ) fieldsAndValues = new Hashtable();
		fieldsAndValues.put(fieldName, valueStr);
	}
	var getDDocName = function(){
		return dDocName;
	}
	this.getDDocName = getDDocName;
	var setDDocName = function(v){
		dDocName = v;
		//if docName is present user is editing and service should be switched to checkout.
		idcServiceName = "FS_CHECK_OUT";
	}
	var setCloneDDocName = function(v){
		dDocName = v;
		//do not perform check-out when creating new item based on existing
		idcServiceName = "FS_GET_FORM";
	}
	this.setCloneDDocName = setCloneDDocName;
	this.setDDocName = setDDocName;
		var getOrigAccount = function()
	{
		return origAccount;
	}
	this.getOrigAccount = getOrigAccount;
	var setOrigAccount = function(v)
	{
		origAccount = v;
	}
	this.setOrigAccount = setOrigAccount;
	/** dID **/
	var getdID = function(){
		return dID;
	}
	this.getdID = getdID;
	var setdID = function(v){
		dID = v;		
	}
	this.setdID = setdID;
	/** dID **/
	/*********/
	var getOrigInDate = function()
	{
		return origInDate;
	}
	this.getOrigInDate = getOrigInDate;
	var setOrigInDate = function(v)
	{		
		origInDate = v;
	}
	this.setOrigInDate = setOrigInDate;
	this.setPlaceHolderName = function(placeHolderStr){
		placeHolderName=placeHolderStr;
	}
	this.setSiteId = function(locStr){
		siteId=locStr;
	}
	var doCreate = function(regionDefinition) {
		var u = getUrl(regionDefinition);
		fsEditorPopup( u );
	}
	this.doCreate = doCreate;
	var getUndoCheckOutUrl = function(){
		var domainPart = "";
		var returnValue = domainPart + serviceRoot + "?IdcService=FS_UNDO_CHECKOUT_BY_NAME&IsJson=1";
		if (getDDocName()) returnValue += "&dDocName=" + getDDocName();
			returnValue += "&OrigInDate="+getOrigInDate() + "&OrigDocAccount=" + getOrigAccount() + "&dID=" + getdID();	
		return returnValue;
	}
	this.getUndoCheckOutUrl = getUndoCheckOutUrl;
	var getUrl = function(regionDefinition) {
		var domainPart = "";
		var returnValue = domainPart + serviceRoot + "?IdcService=" + idcServiceName;
		if (getDDocName()) returnValue += "&dDocName=" + getDDocName();
		var str = "";
		for (var i=0; i<fieldsAndValues.getLength(); i++){
			var valuePair = fieldsAndValues.getPairValue(i);			
			str += "&" + valuePair.getName() + "=" + valuePair.getValue();
		}		
		returnValue += str;
		returnValue += "&xRegionDefinition=" + regionDefinition;
		returnValue += "&ssDefaultDocumentToken=SSContributorDataFile";
		//returnValue += "&xWebsiteObjectType=";
		//returnValue += "&IsJson=1";
		return returnValue;
	}
	this.getUrl = getUrl;
	var switchContentCB = function(){
		setTimeout( "WCM.ReloadURL();", 2000 );
	}
	//placeholderName is optional parameter which may be used to override previously set attributes
	var switchContent = function(placeHolderStr){ 
		if ( !placeHolderStr || placeHolderStr=="" || typeof(placeHolderStr)=='undefined') placeHolderStr = placeHolderName;
		if ( placeHolderStr == "" ) {
			alert( 'please specify a placeholder' );
			return;
		}
		var jsonBinder = new WCM.Idc.JSONBinder();
		jsonBinder.SetLocalDataValue('IdcService', 'SS_SWITCH_REGION_ASSOCIATION');
		var dName =getDDocName();
		jsonBinder.SetLocalDataValue( 'primaryUrl' , dName);
		var fieldName="siteId";
		jsonBinder.SetLocalDataValue(fieldName, fieldsAndValues.get(fieldName));
		fieldName="nodeId";
		jsonBinder.SetLocalDataValue(fieldName, fieldsAndValues.get(fieldName));
		fieldName="siteId";
		jsonBinder.SetLocalDataValue(fieldName, fieldsAndValues.get(fieldName));
		jsonBinder.SetLocalDataValue('region', placeHolderStr);
		jsonBinder.Send(serviceRoot, switchContentCB);
		
	}
	this.switchContent = switchContent;
	var toString = function(){
		var str="";		
		str += fieldsAndValues.toString() + "\n";
		str += "serviceRoot=" + serviceRoot + "\n";
		str += "placeHolderName=" + placeHolderName + "\n";
		str += "infoBinder=" + infoBinder.toString();		
		return str;		
	}
	//pulishing method
	this.toString = toString;
}
var isHandlerInitialized=false; //lippu
function editContent(regionDefinition, placeHolderStr){
	if ( !regionDefinition || regionDefinition=="" ) {
		//alert( "createNewArticle(regionDefinition) function's parameter is empty" );
		return;
	}
	//if ( !isHandlerInitialized || !cdfHandler) 
	nullifyGlobalCDFHandler();
	initHandler();
	if (placeHolderStr!=null) {
		cdfHandler.setPlaceHolderName(placeHolderStr);
	}
	cdfHandler.doCreate(regionDefinition);
}
function switchContent(placeHolderStr){
	if ( !isHandlerInitialized || !cdfHandler) return;
	//if ( !placeHolderStr || placeHolderStr=="" ) placeHolderStr = cdfHandler.
	cdfHandler.switchContent(placeHolderStr);
}
function nullifyGlobalCDFHandler(){
	cdfHandler=null;
	isHandlerInitialized=null;
}

function editNewsLetter(locId){
	nullifyGlobalCDFHandler();
	initHandlerForNewsLetter(locId);
	fsEditorPopup(cdfHandler.getUrl("RD_GEN_UUTINEN"));
}

function editPublicNewsLetter(locId,editAccepted,xWebSites){
	nullifyGlobalCDFHandler();
	initHandlerForPublicNewsLetter(locId,editAccepted,xWebSites);
	fsEditorPopup(cdfHandler.getUrl("RD_GEN_UUTINEN"));
}

function editEvent(locId){
	nullifyGlobalCDFHandler();
	initHandlerForEvents(locId);
	fsEditorPopup(cdfHandler.getUrl("RD_GEN_TAPAHTUMA"));
}

function editBanner(locId, placeHolderStr){
	nullifyGlobalCDFHandler();
	initHandlerForBanner(locId);
	fsEditorPopup(cdfHandler.getUrl("RD_GEN_BANNER"));
}

function editFeedback(){
	nullifyGlobalCDFHandler();
	initHandlerForFeedback();
	fsEditorPopup(cdfHandler.getUrl("RD_GEN_PALAUTE"));
}
function editGeneralFeedback(){
	nullifyGlobalCDFHandler();
	initHandlerForGeneralFeedback();
	fsEditorPopup(cdfHandler.getUrl("RD_GEN_PALAUTE"));
}

function editDocumentLibrary(locId){
	nullifyGlobalCDFHandler();
	initHandlerForDocumentLibrary(locId);
	fsEditorPopup(cdfHandler.getUrl("DL"));
}

function setImageCaptionWidth(){
	// set image caption width. For IE7.
	var captionElement = document.getElementById("newscaption");
	
	if(captionElement && captionElement!=null){
		var newImg = new Image();
		var newImgSrc = document.getElementById("newsimg").src;
		newImg.src = newImgSrc;
		var width = newImg.width;
		if(width>550){
			width=550;
			document.getElementById("newsimg").width = width;
		}
		
		captionElement.style.width = width+"px";
	}
}


// Javascript to clear SP cookies on Shibboleth logout.
// Redirects to IDP logout page, if cookie(s) were found.
// Modified: 17.11.2010

//
// The IDP logout uri
//
var logout_uri = 'https://idp.tut.fi/idp/logout' ;

//
// The logout
//
function shib_logout(first, second) {

  var had_session = "0" ;

  if (document.cookie && document.cookie != '') {

    var allcookies = document.cookie.split(';') ;
    var expires    = new Date() ;

    expires.setDate(expires.getDate() - 1) ;

    for (var i = 0; i < allcookies.length; i++) {
      var name = allcookies[i].split("=") ;
      name     = decodeURIComponent(name[0].replace(/^ /, '')) ;

      if (name.match(/^_shib/)) {
        document.cookie = name+"=_session_invalidated_; expires="+expires.toUTCString()+"; path=/";
        had_session = "1" ;
      }
    }
  }

  if (had_session > 0) {
    if (first) {
      logout_uri = logout_uri+"?"+first ;
      if (second) {
        logout_uri = logout_uri+"&"+second ;
      }
    }
    window.location = logout_uri ;
  } 
}


