// JavaScript Document
// utilities.js
// cleans up html code
var timer;

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function setBackgroundImage (id, imageURL) {
  if (document.layers)
    document[id].background.src = imageURL == 'none' ? null : imageURL;
  else if (document.all)
    document.all[id].style.backgroundImage = imageURL == 'none' ? 'none' : 'url(' + imageURL + ')';
  else if (document.getElementById)
    document.getElementById(id).style.backgroundImage = imageURL == 'none' ? 'none' : 'url(' + imageURL + ')';
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function showTabs(elem){
	$(elem).animate({ 
		top: "0px",
		height: "88px"
	  }, 700);	
}
function hideTabs(elem){
	$(elem).animate({ 
		top: "63px",
		height: "25px"
	  }, 700);	
}

function jqAlert(text){
	<!---The below div is a popup dialog box set for alerts and confirmations--->
	var height = 200;
	var width = 300;
	if (arguments.length == 2) height=arguments[1];
	if (arguments.length == 3) width=arguments[2];
	if( $("#popupDialog").length > 0){
		$('#popupDialog').dialog("destroy");
		$('#popupDialog').remove();	
	}
	$("body").append('<div id="popupDialog" class="text"><p class="text">'+text+'</p></div>');
	/*$('#popupDialog p').find("a").each(function(i) {
		$(this).click(function(){
		$('#popupDialog').dialog('close');return true;		
		}); 
	});*/


	$('#popupDialog').dialog({
		autoOpen: false,
		bgiframe: true,
		closeOnEscape: true,
		modal:true,
		height: height+50, //account for the giant ok button!
		width: width+50, //just because of the design
		title: "ALERT",
		position: ['center',100],
		buttons: {
			'Ok': function() { $(this).dialog('close');return true;}
		}
	});
	$('#popupDialog').dialog('open').html('<p class="text">'+text+'</p>');
	return true;
}
function jqConfirm(text){
	var height = 200;
	var width = 300;
	if (arguments.length == 2) height=arguments[1];
	if (arguments.length == 3) width=arguments[2];
	if( $("#popupDialog").length > 0){
		$('#popupDialog').dialog("destroy");
		$('#popupDialog').remove();	
	}
	$("body").append('<div id="popupDialog" class="text"><p class="text">'+text+'</p></div>');
	/*$('#popupDialog p').find("a").each(function(i) {
		$(this).click(function(){
		$('#popupDialog').dialog('close');return true;		
		}); 
	});*/
    
	var cancel = function() {
    //close the dialog
    $("#myDialog").dialog("close");
		return false;
    }
	 var getOK = function(){
		 $("#myDialog").dialog("close");
		 return true;
	 }
	$('#popupDialog')
		.html('<p class="text">'+text+'</p>')
		.dialog({
			autoOpen: true,
			bgiframe: true,
			closeOnEscape: false,
			modal:true,
			height: height+50, //account for the giant ok button!
			width: width+50, //just because of the design
			title: "Confirmation Required",
			position: ['center',100],
			buttons: {
				'Ok': getOK,
				'Cancel': cancel
	
			}
	});
	
	
}
function showPublicationAlert(value){
	if(value.toLowerCase() == "no" || value.toLowerCase() == "i don't know"){
	jqAlert('Figure and table revision requires upgrade to premium or superior editing level.  Premium editing is sufficient for adding revision of tables only, or of 1-2 figures only. If you have multiple figures that you would like improved, you should select superior editing level to allow hourly charges for the additional time.  If the text itself also calls for extensive rewriting, substantial length reduction and/or reorganization, then superior editing level should be selected as these revisions to text will use up additional time afforded by selecting premium (mid) level editing.',300);
	}
	return;
}

function showPaymentTypeAlert(el,elSelIndex){
	var text = el.options[elSelIndex].text
	if(text.toLowerCase() == "bank transfer"){
		jqAlert('Money transfer transactions are associated with fees which will be added to your invoice.',200);
	}
	return;
	
}
function pauseMe(timer)
{
timer=setTimeout("pauseMe(timer)",5000);
}
function pause(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    }

function assignProject (drag,drop){

	var projectID="";
	var userID="";
	var okCancel = "";
	var dragSplit = drag.split("_");
	var dropSplit = drop.split("_");
	var dragID = dragSplit[1];
	var dropID = dropSplit[1];
	var dragType = dragSplit[0];
	var dropType = dropSplit[0];
	var alerttext = "order";
	if (dragType == dropType ) {
		if(dragType == 'u') alerttext = "editor";
		jqAlert("You seem to have dragged an "+ alerttext +" onto an " + alerttext + ".  Try dragging an editor onto an order or vice versa.");
		return;
	}
	if (dragType == 'u' && dropType == 'p'){
		userID = dragID;
		projectID = dropID;
	} else if (dragType == 'p' && dropType == 'u'){
		userID = dropID;
		projectID = dragID;
	}
	//alert(userID);
	//alert(projectID);
	if( $("#confirmDialog").length > 0){
		$('#confirmDialog').dialog("destroy");
		$('#confirmDialog').remove();		
	}
	$("body").append('<div id="confirmDialog" class="text"><p class="text">Are you sure you want to assign this order?</p></div>');
	$('#confirmDialog').dialog({
		autoOpen: false,					 
		modal:true,
		title: "Please confirm.",
		buttons: {
			'Ok': function() { $(this).dialog('close'); postStuff(projectID,userID);},
			'Cancel': function() { $(this).dialog('close');}
		}
		
	});

	$('#confirmDialog').dialog('open').html('<p class="text">Are you sure you want'+getOrderInfo(projectID,userID)+'?</p>');
	return;
};

function getOrderInfo(projectID,userID){
	return $.ajax({
			  type: "POST",
			  url: "/project/getEditorProjectAJAX.cfm",
			  contentType: "application/x-www-form-urlencoded", //default is application/x-www-form-urlencoded
			  dataType: "text", //The type of data that you're expecting back from the server: xml,html,script,json,text
			  data: '&pid='+projectID+'&uid='+userID,
			  async: false
			 }).responseText;

	
	
}
function sendReferralEmail(f){
	var formname = "#"+f.id;
	var formaction = $(formname).attr("action");
	var formmethod = $(formname).attr("method");
	var serializeForm = $(formname).serialize();
	$.ajax({
	  type: formmethod,
	  url: formaction,
	  contentType: "application/x-www-form-urlencoded", //default is application/x-www-form-urlencoded
	  dataType: "text", //The type of data that you're expecting back from the server: xml,html,script,json,text
	  data: serializeForm,
	  success: function (data, textStatus) {
		  // data could be xmlDoc, jsonObj, html, text, etc...
		  $("#resultsForm").html($.trim(data));
		  if ($.trim(data).toUpperCase().substring(0,5) == "ERROR"){
			  $("#resultsForm").append('<div id="showForm" class="text" style="float:left;"><a href="javascript:;" onclick="showForm(\'xx\');" title="Try again">Try again</a></div>');
		  }else{
		  	$("#resultsForm").append('<div id="showForm" class="text" style="float:left;"><a href="javascript:;" onclick="showForm();" title="Send Another">Send another referral</a></div>');
		  }
		  $("#resultsForm").append('<div id="closeDiv" class="text" style="text-align:right;float:right;"><a href="javascript:;" onclick="$(\'#tellColleague\').slideUp(\'slow\');showForm();" title="Close this window"><span style="color:red;font-size:small; ">Close</span></a></div>');
		  this; // the options for this ajax request
		},
	  error: function (XMLHttpRequest, textStatus, errorThrown) {
		  // typically only one of textStatus or errorThrown 
		  // will have info
		  jqAlert(XMLHttpRequest);
		  this; // the options for this ajax request
		},
	  complete: function (XMLHttpRequest, textStatus) {
		  this; // the options for this ajax request
		  $("#resultsForm").show();
		  $("#contactForm").hide();
			}
	});	
		return false;
	
}

function showForm(){
	/*if (arguments.length < 1 ) {
		$("#contact_form input[@type='text']").each(function() {
		   $(this).val('');
		  });
	}*/
	clear_form_elements('#contact_form');
	$("#resultsForm").hide();
	$("#contactForm").show();
}

function clear_form_elements(ele) {

    $(ele).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}


function showHideDiv(divName){
	$("#"+divName).toggle();
}

function submitAllPayments(){
	var formsIDList = "";
	var alertErrors = "";
	var postURL = $("#"+document.forms[0].id).attr('action');
	/*$("input[@type='checkbox']").each(function() {
		 this.value = this.checked?'on':'off';
	 });*/
	 $(':checkbox').each(function(){
        if(this.checked) {
            this.checked = false;
        } else {
            this.checked = true;
        }
    });
	for(i=0; i<document.forms.length; i++){
	   	formsID=document.forms[i].id;
		if (document.forms[i].paymentAmount.value != "" && document.forms[i].paymentReferenceNumber.value != ""){
			postURL = $("#"+formsID).attr('action');
			
			serializedForm = $("#"+formsID).serialize();
			
			$.ajax({
			  type: "POST",
			  url: postURL,
			  contentType: "application/x-www-form-urlencoded", //default is application/x-www-form-urlencoded
			  dataType: "text", //The type of data that you're expecting back from the server: xml,html,script,json,text
			  data: serializedForm+"&ajax=yes",
			  success: function (data, textStatus) {
				  // data could be xmlDoc, jsonObj, html, text, etc...
				jqAlert($.trim(data));
				  this; // the options for this ajax request
				},
			  error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
				  alertErrors=alertErrors+errorThrown;
				  this; // the options for this ajax request
				},
			  complete: function (XMLHttpRequest, textStatus) {
				  this; // the options for this ajax request
				}
			});	
			//alert(serializedForm);
			
		 }
		 
	}
	 
	 if (alertErrors != "") alert(alertErrors); else window.location = postURL;
}

function postStuff(projectID,userID){
	$.ajax({
	  type: "POST",
	  url: "/project/addEditorToProject.cfm",
	  contentType: "application/x-www-form-urlencoded", //default is application/x-www-form-urlencoded
	  dataType: "text", //The type of data that you're expecting back from the server: xml,html,script,json,text
	  data: '&pid='+projectID+'&uid='+userID,
	  success: function (data, textStatus) {
		  // data could be xmlDoc, jsonObj, html, text, etc...
		jqAlert($.trim(data));
		  this; // the options for this ajax request
		},
	  error: function (XMLHttpRequest, textStatus, errorThrown) {
		  // typically only one of textStatus or errorThrown 
		  // will have info
		  jqAlert(XMLHttpRequest);
		  this; // the options for this ajax request
		},
	  complete: function (XMLHttpRequest, textStatus) {
		  this; // the options for this ajax request
		  $("#editors").load("/editor/editorAssignmentList.cfm",{},
				function(){makeRowsDragAndDrop();});
		  $("#unassignedProjects").load("/project/projectUnassigned.cfm",{},
				function(){makeRowsDragAndDrop();});
		}
	});	

	return;
}
function makeRowsDragAndDrop(){
	$('.ddrow').droppable("destroy");
	$('.ddrow').draggable("destroy");
	$('.ddrow').hover(function() {
	  $(this).addClass('draghover');
	  $(this).addClass('text');
	}, function() {
	  $(this).removeClass('draghover');
	});

	 $('.ddrow').draggable({
		cursor: 'move',
		cursorAt: {top:5, left:5},
		distance: 2,
		helper: 'clone',
		opacity: 	.75,
		revert: true,
		zIndex: 	1000
	});
	$('.ddrow').droppable({
		accept : '.ddrow', 
		activeClass: 'dropactive', 
		hoverClass:	'drophover',
		tolerance: 'pointer',
		drop: function (e, ui) 
				{
					//alert($(ui.draggable).attr("id")); /* ID of element being dropped */
					//alert( $(this).attr("id") ); /* ID of droppable area */ 
					assignProject($(ui.draggable).attr("id"),$(this).attr("id"));
				}
	});
	
};
var isDirty=false;
var dirtyContinue = false;
function checkDirty(el){
	if (el.value == 'Update Notes') return true;
	if (dirtyContinue) return true;
	if (isDirty){
		if( $("#confirmDialog").length > 0){
			$('#confirmDialog').dialog("destroy");
			$('#confirmDialog').remove();		
		}
		$("body").append('<div id="confirmDialog" class="text"><p class="text">It does not appear that you have saved your updated notes.  If you would like to save your notes, click \'Update Notes\' above.  If you want to discard your notes, click ' +el.value+ ' again to continue.  </p></div>');
		$('#confirmDialog').dialog({
			autoOpen: true,					 
			modal:true,
			title: "Please confirm.",
			buttons: {
				'Ok': function() { $(this).dialog('close'); dirtyContinue = true;}//,
				//'Cancel': function() { $(this).dialog('close');}
			}
			
		});		
	return false;
	} 
	else return true;
	
}
$(document).ready(function() {
	makeRowsDragAndDrop();
  	$('.checkDirty').change(function () {
		isDirty=true;
		$(":submit").click(function () { 
		  return checkDirty(this);
		});

	})
	$('input.biggreenbutton').hover(function() {
	  $(this).addClass('highlightHover');
	}, function() {
	  $(this).removeClass('highlightHover');
	});
	
    
	$('.divtoggle').click(function(){
			var medID = $(this).attr('divID'); 
			var openText = '<< Click to hide Profit/Revenue Totals';
			var closedText = 'Click to show Profit/Revenue Totals >>';
			$('#'+medID).toggle();
			if ($(this).text() == openText)
				$(this).text(closedText);
			else $(this).text(openText);
		});
   
	/*$('.multi-pt').MultiFile({
	  	accept:'', max:3, STRING: {
	   	remove:'Remover',
	   	selected:'Selected: $file',
	   	denied:'Invalid file type: $ext!'
	  }
	 });
	$('#intheNews').hover(
		function() { //OVER function
			showTabs("#intheNews");
		},		//end over function
		function() { //OUT function
			hideTabs("#intheNews");
		}//end out function	
	);//end hover function
	$('#upcomingEvents').hover(
		function() { //OVER function
			showTabs("#upcomingEvents");	
		},		//end over function
		function() { //OUT function
			hideTabs("#upcomingEvents");
		}//end out function	
	);//end hover function
	$("#intheNewsContent").load("/getnews.cfm");
	$("#upcomingEventsContent").load("/getevents.cfm");*/
});//end document ready