
/* global vars */

    // ajax
    var xmlhttp = null; // http requests
	var xmlDoc = null; // local xml
    
    // partner system
    var _ps_changed = new Array ( 1000 );
    var _ps_locked = new Array ( 1000 );
    var _ps_percent = new Array ( 1000 ); // default "no"
	var _ps_on_lock_chang_warning = new Array ( 1000 );  // set [productid] to true if "lock change" warning should be displayed
	var _ps_pct_warning = new Array();
	
/* global vars */

// event handlers
onerror=handleErr;


function PopUp ( todo, list, agreement, height, width, typeid )
{
	if ( !height ) height = 150;
	if ( !width ) width = 340;
	if( !typeid ) typeid = 0;

	var properties = "width="+width+",height="+height+",alwaysRaised=yes,dependent=yes,hotkeys=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no";
	window.open ( "?op=sa&go=pop&todo=" + todo + "&list=" + list + "&id=" + agreement + "&typeid="+typeid, "AddRule", properties );
	return false;
}
function ReloadParent ( )
{
	window.opener.location = window.opener.location;
	self.close();
	return true;
}



function handleErr(msg,url,l)
{
	txt="There was an error on this page.\n\n";
	txt+="Error: " + msg + "\n";
	txt+="URL: " + url + "\n";
	txt+="Line: " + l + "\n\n";
	txt+="Click OK to continue.\n\n";
	alert(txt);
	return true;
}


function loadXMLDoc ( url, recieveFunction )
{
	// code for IE
	if (window.ActiveXObject)
	{
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.onreadystatechange = recieveFunction;
		xmlhttp.open("GET",url,true);
		xmlhttp.send();
	}
	// code for Mozilla, etc.
	else if (window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = recieveFunction;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(false);
	}
}
function xmlHTTPSuccess ( )
{
	var state = xmlhttp.readyState;

	// if xmlhttp shows "loaded"
	if ( state == 4 )
	{
    	// if "OK"
		var status = xmlhttp;
    	if (status.status == 200)
    		return xmlhttp.responseText;
    	else
    	{
		   	alert("Problem retrieving XML data");
			return false;
    	}
	}

	return false;
}

function MoveUp ( nid, sid )
{	loadXMLDoc ( document.location.protocol + '//' + document.location.host + document.location.pathname + '?op=nls&prelink=MoveUp&nid=' +nid+ '&sid=' +sid, reloadLists );}
function MoveDown ( nid, sid )
{	loadXMLDoc ( document.location.protocol + '//' + document.location.host + document.location.pathname + '?op=nls&prelink=MoveDown&nid=' +nid+ '&sid=' +sid, reloadLists );}
function AddPapers ( aid, nid )
{	loadXMLDoc ( document.location.protocol + '//' + document.location.host + document.location.pathname + '?op=nls&prelink=adArticle&article=' + aid + '&nid=' +nid, reloadLists );}
function RemovePapers( aid, nid )
{	loadXMLDoc ( document.location.protocol + '//' + document.location.host + document.location.pathname + '?op=nls&prelink=removeArticle&article=' + aid + '&nid=' + nid, reloadLists );}

function ReloadNewsletterStoryList ( )
{
	var response = xmlHTTPSuccess ( );

	if ( response != false )
	{
		document.getElementById('letterid').innerHTML = response;

		// reload box with stories left
		var nid = document.getElementById ( 'nid' ).value;
		var week = document.getElementById ( 'selectedweek' );
		var selectedweek = week.options[week.selectedIndex].text;
		var host = document.location.protocol + '//' + document.location.host + document.location.pathname;

		loadXMLDoc ( host + '?op=nls&prelink=NonNLArticles&nid=' + nid + '&week=' + selectedweek, ReloadStoryList );
	}

	return 1;
}
function ReloadStoryList ( )
{
	var response = xmlHTTPSuccess ( );

	if ( response!=false )
		document.getElementById('storiesid').innerHTML = response;

	return 1;
}
function reloadLists ()
{
	var response = xmlHTTPSuccess ( );

	if ( response!=false )
		ReloadStoryBoxes ( );

	return 1;
}
function ReloadStoryBoxes ( )
{
	// reload box with newsletterstories
	var nid = document.getElementById ( 'nid' ).value;
	var host = document.location.protocol + '//' + document.location.host + document.location.pathname;
	loadXMLDoc ( host + '?op=nls&prelink=NLArticles&nid=' + nid, ReloadNewsletterStoryList );

	return 1;
}


// editing nls
function ReplaceBannerImage (prefix)
{
	var ImgLst = document.getElementById(prefix+'SelectImage');
	var Image = document.getElementById(prefix+'PreviewImage');
//	alert(ImgLst+" "+Image);
	if ( Image && ImgLst )
	{
		var Link = document.getElementById(prefix+'link');
		if ( Link )
		{
			// if url exists, warn people about it
			if ( ImgDetails[ImgLst.value]['url'] )
				displayDIV(prefix+'urlwarning1', true);
			else
				displayDIV(prefix+'urlwarning1', false);

			displayDIV(prefix+'urlwarning', false);

			// update url
			Link.value = ImgDetails[ImgLst.value]['url'];
		}

		// display selected image
		Image.src = ImgDetails[ImgLst.value]['img'];
	}
	else
		return false;

	return true;
}

function addzip()
{
	var PreZip = document.getElementById('preZip');
	var ZipLst = document.getElementById('zipLst');

	if ( ZipLst && PreZip )
	{
		if ( !PreZip.value )
		   return false;

		if ( ZipLst.value )
			ZipLst.value += ", ";

    	ZipLst.value += PreZip.value;
	}
    else
    	return false;

	return true;
}

function displayDIV(div, show)
{
	var myElement = document.getElementById(div);

	if ( myElement )
	{
		if ( show == true )
			myElement.style.display = "";
		else if ( show == false )
			myElement.style.display = "none";
	}
}

function showDIV(objDiv)
{
	var myElement = document.getElementById(objDiv);

	if ( myElement )
	{
		if (myElement.style.display == "none")
			myElement.style.display = "";
		else						
			myElement.style.display = "none";
	}
}


/* partner system functions */
function ActionData(id) // if the product is an action let the user write name and description
{
	var products = document.getElementById("product_"+id);
	if ( products[products.selectedIndex].value =="action" )
	{
		document.getElementById("actiondata_"+id).disabled="";
		document.getElementById("actiondata_"+id).style.display = "";
		if ( document.getElementById("actiondata_"+id).value=="" )
			document.getElementById("actiondata_"+id).value="Skriv produktnavn...";
	}
	else
	{
		document.getElementById("actiondata_"+id).disabled="disabled";
		document.getElementById("actiondata_"+id).style.display = "none";
		if ( document.getElementById("actiondata_"+id).value!="" )
			document.getElementById("actiondata_"+id).value="";
	}
}

function DK2INT ( value )
{
	value = value.replace ( ".", "" );
	value = value.replace ( ",", "." );
	return 100 * parseFloat ( value, 10 );
}
function INT2DK ( value )
{
//	value = value/100;
//	value = value + "";
//	value = value.replace ( ".", "," );

	value = value + ""; // change int to str

	if ( value.length > 2 )
	{
		var firstpart = value.substr ( 0, value.length-2 );
		var lastpart = value.substr ( value.length-2, value.length );
		var value= firstpart +","+ lastpart;
	}
	else if ( value.length == 2 )
		value = "0," + value;
	else if ( value.length == 1 )
		value = "0,0" + value;
	else if ( value.length == 0 )
		value = "0,00";

	return value;
}
function calcPercentage ( id )
{
	var pco = DK2INT ( document.getElementById ( "price_costumer_"+id ).value );
	var percentMR = parseInt ( document.getElementById ( "percent_mr_"+id ).innerHTML, 10 );
	var percentPA = parseInt ( document.getElementById ( "percent_partner_"+id ).innerHTML, 10 );

	document.getElementById ( "price_partner_"+id ).value = INT2DK ( Math.floor ( pco * ( percentPA/100 ) ) );
	document.getElementById ( "price_mr_"+id ).value = INT2DK ( Math.ceil ( pco * ( percentMR/100 ) ) );

	ValidateMinReklameShareOfProductPriceSilent ( id );
}
function calc ( id, changed )
{
	var pco = DK2INT ( document.getElementById ( "price_costumer_"+id ).value );
	var pmr = DK2INT ( document.getElementById ( "price_mr_"+id ).value );
	var ppa = DK2INT ( document.getElementById ( "price_partner_"+id ).value );
	var percentMR = parseInt ( document.getElementById ( "percent_mr_"+id ).innerHTML, 10 );
	var percentPA = parseInt ( document.getElementById ( "percent_partner_"+id ).innerHTML, 10 );

	if ( ( _ps_locked[id]=="mr" && changed=="partner" ) || ( _ps_locked[id]=="partner" && changed=="mr" ) )
		document.getElementById ( "price_costumer_"+id ).value = INT2DK ( pmr + ppa );
	else if ( ( _ps_locked[id]=="mr" && changed=="costumer" ) || ( _ps_locked[id]=="costumer" && changed=="mr" ) )
		document.getElementById ( "price_partner_"+id ).value = INT2DK ( pco - pmr );
	else if ( ( _ps_locked[id]=="costumer" && changed=="partner" ) || ( _ps_locked[id]=="partner" && changed=="costumer" ) )
		document.getElementById ( "price_mr_"+id ).value = INT2DK ( pco - ppa );
	else if ( ( _ps_locked[id]=="costumer" && changed=="mr" ) || ( _ps_locked[id]=="mr" && changed=="costumer" ) )
		document.getElementById ( "price_partner_"+id ).value = INT2DK ( pco - pmr );
	else if ( _ps_locked[id]=="share" && changed=="costumer" )
	{
		document.getElementById ( "price_partner_"+id ).value = INT2DK ( Math.floor ( pco/100*percentPA ) );
		document.getElementById ( "price_mr_"+id ).value = INT2DK ( Math.ceil ( pco/100*percentMR ) );
		return;  /* no need for recalc % */
	}

	/* recalc % from new values*/
	var pco = DK2INT ( document.getElementById ( "price_costumer_"+id ).value );
	var pmr = DK2INT ( document.getElementById ( "price_mr_"+id ).value );
	var ppa = DK2INT ( document.getElementById ( "price_partner_"+id ).value );

	document.getElementById ( "percent_partner_"+id ).innerHTML = Math.floor((ppa/pco)*100);
	document.getElementById ( "percent_mr_"+id ).innerHTML = Math.ceil((pmr/pco)*100);
	
	ValidateMinReklameShareOfProductPriceSilent ( id );
}

function ValidateMinReklameShareOfProductPrice()
{
	var x;
	var products = "";
	for ( x in _ps_pct_warning )
		if ( _ps_pct_warning[x] )
			products += x + ", ";

	if ( products != "" )
		return confirm ( "MinReklame ApS tjener mindre end 30% på produkt "+ products +"!! Er du sikker på at det er OK?" );
	else
		return true;
}
		 
function ValidateMinReklameShareOfProductPriceSilent ( id )
{
	var pco = DK2INT ( document.getElementById ( "price_costumer_"+id ).value );
	var pmr = DK2INT ( document.getElementById ( "price_mr_"+id ).value );

	if ( Math.ceil((pmr/pco)*100)<30 )
		_ps_pct_warning [ id ] = true;
	else 
		_ps_pct_warning [ id ] = false;
}
function TestLockChange(id)
{
	if ( _ps_on_lock_chang_warning[id] == true )
	{
		_ps_on_lock_chang_warning[id] = !confirm ( "Du får nu mulighed for at ændre på andre parametre end den oprindelige kampagneaftale tillod." );
		return !_ps_on_lock_chang_warning[id];
	}

	return true;
}
function AreWeWithinBudget ( id )
{
	var bud = document.getElementById("BudgetMargin").innerHTML; // Total budget minus all products garuatanteed to partners
	if ( bud != "no budget" ) // do we use budget at all ?
	{
		bud = parseInt ( bud );
		var amount = parseInt ( document.getElementById("max_"+id).value ); // amount of current product ( this can change if user is editing )
		var cur = 0;

		if ( cur = document.getElementById("current_"+id).innerHTML ) // product original start price, before changed this session ( amount * price )
			bud = parseInt ( bud ) + parseInt ( cur ); // we should not deduct the sum of the current product - since we may be modifying it...

		var costumer = DK2INT ( document.getElementById("price_costumer_"+id).value ); // price the costumer is currently paying
		var current = (amount * costumer); // total current price of pruduct

		if ( bud < current ) // if we exceed the budget margin, make a warning
			alert ( "Du skal være opmærksom på at du nu overskrider det samlede budget! \n\n(Budget tilbage: kr. " + INT2DK(bud) + ", Garanteret til partnere: kr. " + INT2DK(current) + ")" );
	}
}

function EnableStuff (id)
{
	if ( _ps_percent[id] == "no" || _ps_locked[id] != "costumer" )
	{
		document.getElementById("minus_mr_"+id).disabled = true;
		document.getElementById("plus_mr_"+id).disabled = true;
		document.getElementById("minus_partner_"+id).disabled = true;
		document.getElementById("plus_partner_"+id).disabled = true;
	}
	else if ( _ps_percent[id] == "yes" && _ps_locked[id] == "costumer" )
	{
		document.getElementById("minus_mr_"+id).disabled = false;
		document.getElementById("plus_mr_"+id).disabled = false;
		document.getElementById("minus_partner_"+id).disabled = false;
		document.getElementById("plus_partner_"+id).disabled = false;
	}

	document.getElementById("price_costumer_"+id).readOnly = false;
	document.getElementById("price_mr_"+id).readOnly = false;
	document.getElementById("price_partner_"+id).readOnly = false;

	if ( _ps_locked[id] == "costumer" )
		document.getElementById("price_costumer_"+id).readOnly = true;
	else if ( _ps_locked[id] == "mr" )
		document.getElementById("price_mr_"+id).readOnly = true;
	else if ( _ps_locked[id] == "partner" )
		document.getElementById("price_partner_"+id).readOnly = true;
	else if ( _ps_locked[id] == "share" )
	{
		document.getElementById("price_mr_"+id).readOnly = true;
		document.getElementById("price_partner_"+id).readOnly = true;
	}
}

function allowPercent ( id, todo )
{
	_ps_percent[id] = todo;
	EnableStuff ( id );
}
function mylock ( id, area )
{
	if ( TestLockChange(id) ) // is it okay to change the lock ?
	{
		_ps_locked[id] = area;
		EnableStuff ( id );
		return true;
	}
	else
	{
		document.getElementById ( "lock_" + _ps_locked[id] + "_" + id ).checked = true; // ensure right radio is set 
		return false;
	}
}
function change ( id, area )
{
	var _ps_changed = area;
	calc ( id, area )
	if ( area=='costumer' )
		AreWeWithinBudget (id );
}

function minus ( id, area )
{
	var other = null;
	if ( area == "mr" )
		other="partner";
	else other = "mr";

	var val = parseInt ( document.getElementById("percent_" + area + "_" + id ).innerHTML, 10 );
	document.getElementById("percent_" + area + "_" + id ).innerHTML = --val;
	val = parseInt ( document.getElementById("percent_" + other + "_" + id ).innerHTML, 10 );
	document.getElementById("percent_" + other + "_" + id ).innerHTML = ++val;

	calcPercentage ( id );
}
function plus ( id, area )
{
	var other = null;
	if ( area == "mr" )
		other="partner";
	else other = "mr";

	var val = parseInt ( document.getElementById ( "percent_" + area + "_" + id ).innerHTML, 10 );
	document.getElementById ( "percent_" + area + "_" + id ).innerHTML = ++val;
	var val = parseInt ( document.getElementById ( "percent_" + other + "_" + id ).innerHTML, 10 );
	document.getElementById ( "percent_" + other + "_" + id ).innerHTML = --val;

	calcPercentage ( id );
}

function ReloadContactSelector ( senderid, targetid )
{
	// get selected company
	var sel = document.getElementById(senderid);
	var companyid = sel.options[sel.selectedIndex].value;
// window.location = document.location.protocol + '//' + document.location.host + document.location.pathname + '?op=campaign&nohtml=GetContacts&companyid=' + companyid + '&targetid=' + targetid;
// return;
	// issue request
	loadXMLDoc ( document.location.protocol + '//' + document.location.host + document.location.pathname + '?op=campaign&nohtml=GetContacts&companyid=' + companyid + '&targetid=' + targetid, LoadXML );
}
function LoadXML ( )
{
	var response = xmlHTTPSuccess ( );
	if ( response!=false )
	{//alert ( response );
		try
		{
			// IE
			if (window.ActiveXObject)
			{
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async=false;
				xmlDoc.loadXML(response);
			}
			// code for Mozilla, etc.
			else if ( document.implementation.createDocument )
			{
				var parser = new DOMParser();
				xmlDoc = parser.parseFromString(response, "text/xml"); 
			}
		}
		catch ( err )
  		{
  			txt = "There was an error loading xml.\n\n";
  			txt += "Error description: " + err.description + "\n\n";
  			txt += "Click OK to continue.\n\nXML:\n" + response;
		}

		DoTheReload();
	}
}
function DoTheReload ( )
{//alert ( xmlDoc.xml );
	// empty select
	var select = document.getElementById ( xmlDoc.getElementsByTagName("targetid")[0].firstChild.nodeValue );
	var count = select.length;
	if ( count>0 )
		for ( var i=0; i<count; i++ )
			select[0] = null;

	// fill select
	var items = xmlDoc.getElementsByTagName("person");
	if ( items.length>0 )
		for ( var i=0; i<items.length; i++ )
			select.options[i] = new Option ( items[i].getElementsByTagName("name")[0].firstChild.nodeValue, items[i].getElementsByTagName("id")[0].firstChild.nodeValue );
}

function isLeapYear(year){
	if(year%4==0){
		if(year%100==0){
			if(year%400==0){
				return true
			} else {
				return false;
			}
		} else {
			return true;
		}						
	} else {
		return false;
	}
}
function updateDateSelect(idprefix){
	if(!idprefix) 
		idprefix = "";
	else
		idprefix += "_";

	monthSelect = document.getElementById(idprefix+'month');	
	month = monthSelect.options[monthSelect.selectedIndex].value;
	if(month==2){
		yearSelect = document.getElementById(idprefix+'year');
		year = yearSelect.options[yearSelect.selectedIndex].value;
		if(isLeapYear(year)){
			days = 29;
		} else {
			days = 28;
		}
	} else {
		dim = new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
		days = dim[month];
	}
	daySelect = document.getElementById(idprefix+'day');
	current = daySelect.options.length;

	prevIndex = daySelect.selectedIndex;
	
	if(current>days){
		for(i=current-1;i>=days;i--){
			daySelect.remove(i);
		}
	} else if(days>current){
		for(i=current+1;i<=days;i++){
			var optn = document.createElement("option");
			optn.text = i;
			optn.value = i;
			daySelect.options.add(optn);
		}		
	}
	
	if(prevIndex>daySelect.length-1){
		daySelect.selectedIndex=daySelect.options.length-1;
	}
}

var currentTabContent = new Object();
var currentTabLink = new Object();
function showTab(tablink,areaid, std){
	if(!currentTabContent[areaid]){
		currentTabContent[areaid] = document.getElementById(std);
		currentTabLink[areaid] = document.getElementById(std+'_link');
	}
	currentTabContent[areaid].style.display = 'none';
	currentTabLink[areaid].className = 'tab';
	
	currentTabLink[areaid] = tablink;

	contentName = tablink.id.split('_')[0];
	currentTabContent[areaid] = document.getElementById(contentName)
	currentTabLink[areaid].className = 'tabactive';
	currentTabContent[areaid].style.display = 'block';
	createCookie('tabarea_'+areaid,contentName,14);
	

}


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function LinkSelectChange(select){
	if(select.id=='link_to_ipaper'){
		other = document.getElementById('link_to_minreklame');
	} else {
		other = document.getElementById('link_to_ipaper');		
	}	
	if(select.options[select.selectedIndex].value==0){
		other.disabled = false;
	} else {
		other.disabled = true;
	}
}
