
function loadingPanel(show) {
	var x = document.getElementById("loadingimage");
	if (show)	{	
		x.src = "/images/loading.gif";
		} else {
		x.src = "/images/shim.gif";	
		}
	}
function loadIt() {
  $(".datePicker").datepicker({ dateFormat: 'dd/mm/yy' });
  $("#dateRange").click(function() {
    if($(this).is(':checked')){
      $("#dateTo").attr("disabled", false);
      $("#dateFrom").attr("disabled", false);    
     }
     else{
      $("#dateTo").attr("disabled", true);
      $("#dateFrom").attr("disabled", true);
     }
  })
  $("#memberRestrictions").click(function() {
    if($(this).is(':checked')) {
      $("#membersParticipating").attr("disabled",false);
    } else {
      $("#membersParticipating").attr("disabled",true);
    }
  })
}

function loadingWindow(show) {
	if (show) {
		// $.blockUI({ message: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />' }); 
	} else {
		// $.unblockUI(); 	 
	}
}
// constants to define the title of the alert and button text.
var ALERT_TITLE = "Oops!"; 
var ALERT_BUTTON_TEXT = "Ok";
window.onload = function() {
          var scrollTop = parseInt(document.cookie.replace(/scrollTop=([0-9]+)/, '$1'));
         
          if (!isNaN(scrollTop)) {
                  document.body.scrollTop = scrollTop;
									window.scrollTo(0,scrollTop);
					}
}

// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts
if(document.getElementById) {
	//window.alert = function(txt) {
	//	alert(txt);
	//}
}
function deletePSA(psaID) { 
	c = window.confirm('are you sure you wish to completely delete this PSA?');
	if (c) {
		document.location.href = '/intranet/main/deletearrangement.do?psaID=' + psaID;
		}
}

function openDocManager(path) {
	window.open("/fileexplorer/","filemanager","width=780,height=500,toolbar=0,resize=1,statusbar=0");
	}
function menu(ul) {
	var de = document.getElementById(ul);
	if (de.style.display == "none") {
		de.style.display = "block";
	} else {
		de.style.display = "none";
		}
	}

function showhidecontacts() {
		c = document.getElementById("contactList");
		if (c.style.display == "none") {
			// it's hidden
			c.style.display = "block";
		} else {
			c.style.display = "none";
			}
	}

function createCustomAlert(txt) {
	// shortcut reference to the document object
	d = document;

	// if the modalContainer object already exists in the DOM, bail out.
	if(d.getElementById("modalContainer")) return;

	// create the modalContainer div as a child of the BODY element
	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	 // make sure its as tall as it needs to be to overlay all the content on the page
	mObj.style.height = document.documentElement.scrollHeight + "px";

	// create the DIV that will be the alert 
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "alertBox";
	// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	// center the alert box
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

	// create an H1 element as the title bar
	h1 = alertObj.appendChild(d.createElement("h1"));
	h1.appendChild(d.createTextNode(ALERT_TITLE));

	// create a paragraph element to contain the txt argument
	msg = alertObj.appendChild(d.createElement("p"));
	msg.appendChild(d.createTextNode(txt));

	// create an anchor element to use as the confirmation button.
	btn = alertObj.appendChild(d.createElement("a"));
	btn.id = "closeBtn";
	btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
	btn.href = "#";
	// set up the onclick event to remove the alert when the anchor is clicked
	btn.onclick = function() { removeCustomAlert();return false; }

	
}

	function createCompany() {
		window.open("/intranet/main/addcompany.plain?inwindow=true","newcompany","width=450, height=450, scrollbars=1,toolbar=0");
	}
	function createContact() {
	window.open("/intranet/main/addcontact.plain?inwindow=true","newcontact","width=450, height=450, scrollbars=1,toolbar=0");
	
	}

// removes the custom alert from the DOM
function removeCustomAlert() {
	document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}


function drawComponent(result) {
	//
	var psaID = result.PSAID;
	var rGroup = result.RGROUP;
	var rType = result.RTYPE;
	var bodyhtml = result.BODYHTML;
	if (result.TITLEHTML != undefined) {
		result.BODYHTML = result.TITLEHTML + result.BODYHTML;
		}
	/*alert(rGroup + "td");
	alert(document.getElementById(rGroup + "td").innerHTML);
	alert(result.titlehtml);
	alert(result.bodyhtml);*/
	
	document.getElementById(rGroup + "td").innerHTML = result.BODYHTML;
	loadIt();
}

function editComponentDetails(rebateGroup,type,psaID,arrayIndex) {	
		var argumentCollection = new Object(); 
		argumentCollection.aIndex = arrayIndex; 
		argumentCollection.ID = document.getElementById('id_' + arrayIndex).value;
		argumentCollection.title = document.getElementById('title_' + arrayIndex).value; 
		argumentCollection.permissions = document.getElementById('permissions_' + arrayIndex).value;		
		if (type == "meta" || type == "rebate") {
			argumentCollection.details = document.getElementById('details_' + arrayIndex).value;			
		} 
		if (type == "rebate") {
			argumentCollection.outputType = document.getElementById('outputtype_' + arrayIndex).value;	
			argumentCollection.rebateValue = document.getElementById('value_' + arrayIndex).value;			
		}
		$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "editComponentDetails",
		  data: [rebateGroup,type,psaID,argumentCollection],
		  blockUI: true,
			unnamedargs: true,						
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	sayDone(data);
		  }
		});
	
}

function deleteDocument(file,psaID) {
	x = window.confirm("are you sure you wish to permenantly remove this document?");
	if (x) {
				$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "deletePSADocument",
		  data: [file,psaID],
		  blockUI: true,
			unnamedargs: true,						
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	reloadPage(data);
		  }
		});
	}
}

function deleteAppointment(appID) {
	x = window.confirm("are you sure you wish to delete this appointment?");
	if (x) {
		document.location.href="/intranet/main/appointment.do?func=delete&id=" + appID;
	}
}
function sayDone() {
	alert("your update has been saved!");	
	
}

// JavaScript Document
function deleteArrangementElement(type,psaID,elementA) {
	var conf = window.confirm("are you sure you want to remove this element?");
	if (conf) {
		alert("/intranet/main/removeelement.do?psaID=" + psaID + "&element=" + elementA + "&type=" + type);
		window.location.href="/intranet/main/removeelement.do?psaID=" + psaID + "&element=" + elementA + "&type=" + type;
	}
}
function editComponent(group,aID,psaID) {
		$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "showeEditElement",
		  data:[group,aID,psaID],
			unnamedargs: true,
		  blockUI: true,
			serialization: "json",
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	doresult(data);
		  }
		});
}
function doresult(result) {
	document.getElementById(result.RGROUP + "_description_" + result.ARRAYIND).innerHTML = result.BODYHTML;
	loadIt();	
}

function addcomponent(componentType,componentGroup,psaID) {
	// nothing to do
			if (window.innerHeight)
	{
		  pos = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		pos = document.documentElement.scrollTop
	}
	else if (document.body)
	{
		  pos = document.body.scrollTop
	}
	document.cookie = 'scrollTop=' + pos;

		$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "createElement",
		  data: [componentType.value,componentGroup,psaID],
			unnamedargs: true,			
		  blockUI: true,
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	drawComponent(data);
		  }
		});
}
function deleteComment(postID) {
	// nothing to do
	var conf = window.confirm("are you sure you want to remove this comment?");
	if (conf) {
		$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "deletePost",
		  data: [postID],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	reloadPage(data);
		  }
		});
	}
}
function deletePost(postID) {
	// nothing to do
	var conf = window.confirm("are you sure you want to remove this Post and it's comments?");
	if (conf) {
	$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "deletePost",
		  data: [postID],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	goHome(data);
		  }
		});
	}
}

function goHome() {
	document.location.href = '/intranet/main/';
	}



function switchMode(what,arg) {
	$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "switchMode",
		  data: [what,arg],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	reloadPage(data);
		  }
		});
}
function editStep(cArray,sArray,psaID) {
	loadingWindow(true);	
	var stepFrom = document.getElementById("step_from_i_" + cArray + "_" + sArray).value;
	var stepTo = document.getElementById("step_to_i_" + cArray + "_" + sArray).value;	
	var stepValue = document.getElementById("step_value_i_" + cArray + "_" + sArray).value;		
	$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "editStep",
		  data: [stepFrom,stepTo,stepValue,cArray,sArray,psaID],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	doneEditStep(data);
		  }
		});
	}

function moveUp(type,psaID,elementA) {
		$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "moveElementUp",
		  data: [type,elementA,psaID],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	reloadPage(data);
		  }
		});
	}

function doneEditStep(result) {
	fromtd = document.getElementById("stepvalue_from_" + result.CARRAY + "_" + result.SARRAY);
	totd = document.getElementById("stepvalue_to_" + result.CARRAY + "_" + result.SARRAY);
	valuetd = document.getElementById("stepvalue_value_" + result.CARRAY + "_" + result.SARRAY);	
	fromtd.innerHTML = result.FROM;
	totd.innerHTML = result.TO;
	valuetd.innerHTML = result.VALUE;	
	atd = document.getElementById("stepvalue_add_" + result.CARRAY + "_" + result.SARRAY);
	atd.innerHTML = "";
	
	}
function getStep(psaID,a,s) {
		$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "getStep",
		  data: [psaID,a,s],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	buildRebate(data);
		  }
		});
	}
	
function addStep(a,psaID) {
	var sfrom = document.getElementById("from_" + a).value;
	var sto = document.getElementById("to_" + a).value;
	var svalue = document.getElementById("value_" + a).value;	
			$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "addStep",
		  data: [a,psaID,sfrom,sto,svalue],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	reloadPage(data);
		  }
		});
	}
function delStep(c,s,psaID) {
			$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "delStep",
		  data: [c,s,psaID],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	reloadPage(data);
		  }
		});
}
function reloadPage(arg) {
		if (window.innerHeight)
	{
		  pos = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		pos = document.documentElement.scrollTop
	}
	else if (document.body)
	{
		  pos = document.body.scrollTop
	}
	document.cookie = 'scrollTop=' + pos;
	window.location.reload();
	
	}
function buildRebate(result) {
	var f = result.FROM;
	var t = result.TO;
	var v = result.VALUE;
	var sArray = result.SARRAY;
	var cArray = result.CARRAY;
	ftd = document.getElementById("stepvalue_from_" + cArray + "_" + sArray);
	ttd = document.getElementById("stepvalue_to_" + cArray + "_" + sArray);
	vtd = document.getElementById("stepvalue_value_" + cArray + "_" + sArray);
	atd = document.getElementById("stepvalue_add_" + cArray + "_" + sArray);
	fElement = '<input id="step_from_i_' + cArray + '_' + sArray + '" type="text" class="psa_id" value="' + f + '" />';
	tElement = '<input id="step_to_i_' + cArray + '_' + sArray + '" type="text" class="psa_id" value="' + t + '" />';
	vElement = '<input id="step_value_i_' + cArray + '_' + sArray + '" type="text" class="psa_id" value="' + v + '" />';
	bElement = '<input type="button" class="submit" value=" update &raquo;" onclick="editStep(' + cArray + ',' + sArray + ',\'' + result.PSAID + '\');" />';
	ftd.innerHTML = fElement;
	ttd.innerHTML = tElement;
	vtd.innerHTML = vElement;
	atd.innerHTML = bElement;
	
	} 

function changeMonth(dateString) {

		$.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "drawCal",
		  data: dateString,
		  blockUI: false,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	redrawCalendar(data);
		  }
		});
		loadingPanel(true);
}
	
function redrawCalendar(result) {
	calDiv = document.getElementById("calendardraw");
	calDiv.innerHTML = result;
	loadingPanel(false);
	}

function createComponent(cGroup,cType,psaID) {
		/*var groupEl = document.getElementById('discounttd');
		var argumentCollection = new Object();
		argumentCollection.cID = document.getElementById('cid').value;
		argumentCollection.title = document.getElementById('ctitle').value;
		argumentCollection.permissions = document.getElementById('permissions').value;		
		if (cType == "meta") {
			argumentCollection.details = document.getElementById('details').value;
		} else if (cType == "rebate") {
			argumentCollection.value = document.getElementById('rebatevalue').value;
			argumentCollection.calculate = document.getElementById('calculate').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;
			argumentCollection.outputtype = document.getElementById('outputtype').value;			
			
			
		}
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'createComponent',cGroup,cType,psaID,argumentCollection,reloadPage);
*/
}

function reloadNews(sPage) {
	x = document.getElementById("showStories");
	document.location.href = "/intranet/main/default?filter=" + x.value;
	}
function showStory(id) {
	storyTitle = document.getElementById("articletitle_" + id);
	storyBody = document.getElementById("contents_" + id);
  storyBody.style.display = "block";
	storyTitle.href = "/intranet/main/newsstory?id=" + id;
}


function enableFigures(bool) {
	x = document.getElementById("ftitle");

	if (bool) {
		x.disabled = false;
		alert(x.disabled);
		} else {
		x.disabled = true;
		}
	}
function enableCalculation(bool) {
	y = document.getElementById("calculateY");
	n = document.getElementById("calculateN");
	if (bool) {
		y.checked = true;
	} else {
		n.checked = true;
	}
}
function showCompounds(bool) {
	x = document.getElementById("retrospectiveAgainst");
	if (bool) {
		x.disabled = false;
	} else {
		x.disabled = true;
	}
}
function enabledInheritance(bool) {
	z = document.getElementById("inheritFrom");	
	if (bool) {
		z.disabled = false;
	} else {
		z.disabled = true;	
	}
	}
function changePermissions(contactID,oldGroupID) {
	var newID = document.getElementById("groupPermissions").value;
	jQuery.AjaxCFC({
		  url: "/external/listener.cfc",
		  method: "moveUserToGroup",
		  data: [contactID,newID,oldGroupID],
		  blockUI: true,
			unnamedargs: true,			
			blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
		  useDefaultErrorHandler: true,
		  success: function(data) {
		  	//reloadPage(data);
		  }
		}); 
}

$(document).ready(function(){
	
	  $('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
    $("#accordion2").accordion({ autoHeight: false, collapsible: true,active: false, header: 'h3'});
    $(".accordian").accordion({ autoHeight: false,collapsible: true,active: false, header: 'h5',cookie: { expires: 30 } });
		$(".accordion").accordion({ autoHeight: false,collapsible: true,active: false, header: 'h5',cookie: { expires: 30 } });
		$("#tabs").tabs({cookie: {
		  expires: 30
		}});
		$(".recalculate").live("click",function() {
			var x = $(this);
      x.fadeOut(500, function() {
        x.remove(); 
      });
			$.blockUI({message: "<h2>please wait</h2><p>recalculating figures, please be patient...</p>"});
			psaID = jQuery(this).attr("id");
			$.get("/intranet/turnover/calculateFigures?psaID=" + psaID, function(data){
	      $.unblockUI();
				reloadPage(data);
      });
		});
		$('.comp').each(function(){
   var el = this;
   var nn = $(el).attr("id");
   var nNArray = nn.split("_");
   var nodeName = nNArray[0];
   $(el).sortable({
    
  
       placeholder: 'dragging',
       containment: 'parent',
       items: 'div.realtd',
       helper: 'clone',
       opacity: 0.6,
       scroll: true,
       cursor: 'move',
       axis: 'y',
     update: function(event,ui) {           
      var option = $(el).sortable('serialize');     
      var psaID = $("#psaID").val();      
        $.AjaxCFC({
            url: "/external/listener.cfc", 
            method: "dumpData",
            data:[option,psaID,nodeName],
            blockUI: true,
            unnamedargs: true,
            blockMessage: '<h2>Loading, please wait...</h2><img src="/images/loading.gif" />',
            useDefaultErrorHandler: true,
            success: function(data) {
              //reloadPage();
            }
        });     
     },
       delay: 500,
     handle: 'img.handle',
       revert: true
    });
  });
  
});