var $j = jQuery.noConflict();

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_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 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_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  }
  if (errors) alert('The following error(s) occurred:\n'+errors);
  if (errors == '' && document.form1.State.value != 'selected'){
  	allGood();
  }
}

/* functions dependent on jquery */
$j(document).ready(function(){
	
	
	
	$j(".formBody,.shortFormBody").append("<div style='clear:both;'></div>");
	$j(".formBottom,.shortFormBottom").append("<span></span>");
	$j(".formTop,.shortFormTop").append("<span></span>");

	
	$j(".fieldWithErrors input").addClass("inputError");
	$j(".fieldWithErrors select").addClass("inputError");
	$j(".fieldWithErrors").prev("label").addClass("inputError");
 
   
	$j("#addFile").click(function(){
		$j("#addFileForm").show();
		$j("#fileList").hide();
		$j(this).hide();
	});
	$j("#cancelAddFile").click(function(){
		$j("#addFileForm").hide();
		$j("#addFile").show();
		if ($j(".resourceDescription:not(:hidden)").length == 0) {
			$j("#fileList").show();
		} 
	});
	$j("#resourceUpload form").submit(function(){
		$j("#resourceUploadActivity").show();
		$j("#addFileForm").hide();
	});

	$j("#promotion img").click(function(){  
		var wobblerText = "Wobblers (max 3)";  
		var brochureText = "DL Flyers (max 50)";  
		var selectedItem = $j(this).attr("alt");
		$j("#promotion img").removeClass("selected");
		if ( selectedItem == "Wobbler") {
			$j("#selectionText").text(wobblerText);
			$j("#wobblerLabel").text("Wobbler (Selected)");
			$j("#brochureLabel").text("DL Flyer");
		} else if ( selectedItem == "Brochure" ) {
			$j("#selectionText").text(brochureText);
			$j("#wobblerLabel").text("Wobbler");
			$j("#brochureLabel").text("DL Flyer (Selected)");
		}
		$j(".promotionSelection").show();
		$j("#entry_selection").val(selectedItem);
  		$j(this).addClass("selected");   
	})                                 
	    
	
	otherOption("envelope_other","category_envelope");
	otherOption("paper_type_weight_other","category_paper_type_weight");
	otherOption("envelope_size_other","category_envelope_size");
	otherOption("current_source_other","user_current_source");
	      
	$j("#declineQuote").click(function(){  
		if ($j("#job_state_description").val() == "") {
			confirm("Please type a reason for declining the quote in the Comments section");
			$j("#job_state_description").focus();
			return false;
		}
		 $j("#declineQuoteForm").submit();
		 return false;
	});     
	
	$j(".quantityRow").hover(
		function(){
			$j(this).addClass("highlight");
		}, 
		function(){
			$j(this).removeClass("highlight");
		}
	);
	
 	$j(".tip").click(function(){   
		$j(".tipContent").hide();
		$j(this).next().show();  
		return false;
	});      
	
	$j("#first_window_selected,#second_window_selected").change(function(){
			var targetStr = "#" + $j(this).attr("target");
		 	$j(this).val() == "Yes" ? $j(targetStr).show() : $j(targetStr).hide();
  		if ($j(this).hasClass("inputError")) {
				$j(this).parent().prevAll("label").css("color","red");
			}
	});

	$j(".windowFormError").prev(".mm").css("color","red");
	$j(".windowDimensions").each(function() {
		if ($j(this).find(".windowFormError").is("div"))
			$j(this).children(".windowLabel").css("color","red");
	});
	
	$j("#category_print_coverage").change(function(){
		$j(this).val() == "none" ? $j("#printOptions").hide() : $j("#printOptions").show();
	});
	
	$j("#user_out_of_office").click(function(){
		$j(this).is(":checked") ? $j("#owningRep").show() : $j("#owningRep").hide();
		
	});
	
	$j("#textile").toggle(function(){
		$j("#textileSyntax").show();
	},
	function(){
		$j("#textileSyntax").hide();
	});
	
	/* Migrated */
	$j('#preloader').hide();
	$j('#container-1').show(function() {
		$j('#container-1').tabs({ fxFade: true, fxSpeed: 'fast' });
	});	  
	
	
	initLightBox("lightbox_inline");
	initLightBox("lightbox_impact");
	initLightBox("lightbox_flatsheet");
	initLightBox("lightbox_overprinted");        
	
	
	$j('a.quantityLink').click(function() { 
		var quote_text = $j(this).attr('rel');
		var message = "";                   


		if ($j("#purchase_order_no_value").val() == "") {
			alert("Purchase order is required!")
			return false;
        }

		if($j("#colours_front_value").val() == "") {
			alert("Required Colours on Front is required!")
			return false;
		}        
		
		if($j("#colours_back_value").val() == "") {
			alert("Required Colours on Back is required!")
			return false;
		}        
		

		
		if ($j("#purchase_order_no_value").val() == "") {
			message = "\nDo you want to accept this quote?"
		} else {
			message = "\nYour Purchase Order number details will be sent to begin the ordering process.\nDo you want to purchase these envelopes?"
		}
		
		
		
		
		if (confirm(quote_text + message)) {           
			var purchase_order_no = $j("#purchase_order_no_value").val();
			var colours_back = $j("#colours_back_value").val();
			var colours_front = $j("#colours_front_value").val();
			$j("#purchase_order_no").val(purchase_order_no);
			$j("#colours_front").val(colours_front);
			$j("#colours_back").val(colours_back);
			$j("#quantity_form")
				.attr("action", $j(this).attr("href"))
				.submit();
		}		
		return false;
		
	});
 
});

function initLightBox(name) {
	$j('a[@rel*=' + name + ']').lightBox({
		imageBtnPrev: '/images/prevlabel.gif',
		imageBtnNext: '/images/nextlabel.gif',
		imageLoading: '/images/loading.gif',
		imageBtnClose: '/images/closelabel.gif'
	});	
}


function removeResource(resource) {
	$j("#"+resource).hide();
	if ($j(".resourceDescription:not(:hidden)").length == 0) {
		$j("#fileList").show();
	} 
}
function deletingResource(resource){
	$j("#"+resource+" .resourceActivity").show();
	$j("#"+resource+" .resourceDescription").hide();
}

function submitForm () {
	if (confirm("Are you sure?")) {
		$j('#jobsForm').submit();     
	} 
}

function confirmQuote() {   
	if ($j("#job_sap_quote_ref").is("[value='']")) {
		if (confirm('Have you processed this quote in SAP? If so, click "OK" to send the quote. If not, click "Cancel" and enter the quote specifications in SAP.')) {
			$j('#quoteForm').submit();     
		}                                               
	} else {
		$j('#quoteForm').submit();
	}
}

function otherOption(other,list) {
	
	if ($j("#" + other).val() != "") {
		$j("#" + list + " option:last").val($j("#" + other).val());
	}
	
	$j("#" + list).change(function(){                            
		if ($j(this).val() == $j("#" + list + " option:last").val()) {
			$j("#" + other + "_row").show();
		} else {
			$j("#" + other + "_row").hide();
		}
	});
	
	$j("#" + other).blur(function(){                                                                           
		// If the selected option is the last option     
		if ($j("#" + list + " option:selected").val() == $j("#" + list + " option:last").val()) {         
			$j("#" + list + " option:last").val($j("#" + other).val());
		}
	}); 
	
}
    





 