//////////////////////////////////// Nav List Function

// This function checks the nav link list against the filename in the URL and if it matches, it removes the 
// hyperlink from the nav list as well as changing the style of the active page link.

function currentPage(){
	var docLoc=String(document.location);
	var fileName=docLoc.substring((docLoc.lastIndexOf("/")+1), docLoc.length);	
	var nav = document.getElementById('nav');
	var y = nav.getElementsByTagName("li");
	
	for (i=0; i<y.length; i++){
		var fulllink=String(y[i].innerHTML);		
		var pagestring=fulllink.substring(fulllink.indexOf("\"")+1, fulllink.lastIndexOf("\""));		
		var linktext=fulllink.substring(fulllink.indexOf("\>")+1, fulllink.lastIndexOf("\<"));				
		
		if (fileName==""){
			y[0].innerHTML="<b style='color: #2E5DA4; background-color:#FFFFFF'>&gt; "+linktext+"</b>";				
			break;
		}

		else if (pagestring==fileName){			
			y[i].innerHTML="<b style='color: #2E5DA4; background-color:#FFFFFF'>&gt; "+linktext+"</b>";				
			break;
		}		
	}
}

   

///////////////////////////////////////// Processing Form Functions

$(function(){

	/** 
	* Throws up a Quantity error if Total Weight is Less than BATCH
	*/
	function qtyError(obj){
		alert ("Minimum Batch Quantity Must be " + BATCH + " lbs.");
		obj.parent().parent().find(".itemtotal").text("");
		return false;
	}
	
	BATCH = 25;
	BEEF = 2.99;
	PORK = 1.99;
	
	CurrentProcessQty = 0;
	CurrentBlendQty = 0;
	BlendType = "";
	
	// Enter Processing qty - Also Gets the Blend Quantity and runs GetThisTotal
	$(".processqty").blur(function(index) {
	 	 
	 	CurrentProcessQty = parseInt($(this).val());
		CurrentBlendQty = parseInt($(this).parent().parent().find('input:[class=blendqty]').val());
		BlendType = $(this).parent().parent().find('input:radio[name$=blendtype][:checked]').val();
		
		// User has reset the process qty to 0
		if (CurrentProcessQty == 0){
			$(this).parent().parent().find(".itemtotal").text("");									// Set Item's total Price to 0
			$(this).parent().parent().find('input:radio[name$=blendtype]').removeAttr('checked');	// Remove checked blend type
			BlendType = "";																			// Set the BlendType to blank
			$(this).val("");																		// Set the process qty textbox to blank
			$(this).parent().parent().find('input:[class=blendqty]').val("");						// Set the matching blend textbox to blank
			$("#priceamt").text("0.00");															// Set the Sum Total price to 0
		}
		
		// ProcessQty is Greater than the minimum batch qty.  Go ahead and get the total.
		else if (CurrentProcessQty >= BATCH){
			getThisTotal($(this), CurrentProcessQty, CurrentBlendQty, BlendType);
		}
		
		// Process and Blend are greater than minimum batch.  Get total.
		else if (CurrentProcessQty + CurrentBlendQty >= BATCH){
			getThisTotal($(this), CurrentProcessQty, CurrentBlendQty, BlendType);
		}
		
		else {
			qtyError($(this));
		}	 	 
	});

	// Enter Blend qty - Also Gets the Processing Quantity and runs getThisTotal
	$(".blendqty").blur(function(index) {
	 	CurrentBlendQty = parseInt($(this).val());
		CurrentProcessQty = parseInt($(this).parent().parent().find('input:[class=processqty]').val());
		BlendType = $(this).parent().parent().find('input:radio[name$=blendtype]').val();
		
		// If CurrentProcessQty and CurrentBlendQty are Both Zero, 
		// Change the Item total text to "" and remove any selected blend type
		if (CurrentProcessQty == 0 && CurrentBlendQty == 0){
			$(this).parent().parent().find(".itemtotal").text("");
			$(this).parent().parent().find('input:radio[name$=blendtype]').removeAttr('checked');
			$(this).parent().parent().find('input:radio[name$=blendtype]').val("");
			$(this).val("");
			$(this).parent().parent().find('input:[class=processqty]').val("");

		}
		
		// If CurrentBlendQty is Zero and CurrentProcessQty >= to the min Batch,
		// Remove any selected blend types and call the getThisTotal function
		else if (CurrentBlendQty == 0 && CurrentProcessQty >= BATCH)
		{
			$(this).parent().parent().find('input:radio[name$=blendtype]').removeAttr('checked');
			$(this).parent().parent().find('input:radio[name$=blendtype]').val("");
			
			getThisTotal($(this), CurrentProcessQty, CurrentBlendQty, BlendType);
		}
		
		// If the CurrentBlendQty + CurrentProcessQty < min batch , call qtyerror		
		else if (CurrentBlendQty + CurrentProcessQty < BATCH){
			qtyError($(this));
		}
		
		// If the CurrentBlendQty + CurrentProcessQty >= min batch , call getThisTotal
		else if (CurrentBlendQty + CurrentProcessQty >= BATCH){
			BlendType = $(this).parent().parent().find('input:radio[name$=blendtype]:checked').val();
			
			getThisTotal($(this), CurrentProcessQty, CurrentBlendQty, BlendType);
		}
		
		rollUpTotals();		
	});
	
	// Check for Blend Type and Fire off getThisTotal if CurrentBlendQty is Defined
	 $('input:radio[name$=blendtype]').change(function(index) {
		CurrentBlendQty = parseInt($(this).parent().parent().find('input:[class=blendqty]').val());
		CurrentProcessQty = parseInt($(this).parent().parent().find('input:[class=processqty]').val());
		BlendType = $(this).val();

		
		
		if (CurrentBlendQty == 0 || CurrentBlendQty == "" || isNaN(CurrentBlendQty)){
			$(this).removeAttr('checked');
			alert("Please Enter a Blend Weight First.");
			$(this).parent().parent().find('input:[class=blendqty]').focus();
		}
		
		else if (CurrentBlendQty + CurrentProcessQty < BATCH){
			qtyError($(this));
		}
		
		else if(CurrentProcessQty >= BATCH){
			getThisTotal($(this), CurrentProcessQty, CurrentBlendQty, BlendType);	
		}
		
		else{
			getThisTotal($(this), CurrentProcessQty, CurrentBlendQty, BlendType);	
		}
		
		rollUpTotals();
	});
			

	/**
	* This function rolls up line item totals based on user input.
	*/
	
	function getThisTotal(obj, PQ, BQ, BT){
		// Find the price of the item
		 itemPrice = obj.parent().parent().find(".price").text();
		 itemPrice = parseFloat(itemPrice.slice(1));
			
		// If processing only, go ahead and calculate the total.
		if (PQ >= BATCH && (BQ==0 || BQ=="" || isNaN(BQ))){
			obj.parent().parent().find(".itemtotal").text((itemPrice * PQ).toFixed(2));
		}
		
		// Check Whether Blend is Pork or Beef and calculate total accordingly.
		else if (PQ > 0 && BQ > 0 && BT == "Pork"){
				 obj.parent().parent().find(".itemtotal").text(((itemPrice * (PQ + BQ)) + (BQ * PORK)).toFixed(2));
		}
			
		else if (PQ > 0 && BQ > 0 && BT == "Beef"){
				 obj.parent().parent().find(".itemtotal").text(((itemPrice * (PQ + BQ)) + (BQ * BEEF)).toFixed(2));
		}
	
		rollUpTotals();
	
	}
		
});	


/**
* Rolls up the totals from the qty(weight) fields based on weight supplied and price within the table cells
*/

function rollUpTotals(){
	var RunningTotal = 0;

	$(".itemtotal").each(function(){
		ThisTotal = parseFloat($(this).text())
	
		if (!isNaN(ThisTotal)){
			RunningTotal += ThisTotal;	
		}
	});
	
	RunningTotal = roundNumber(RunningTotal,2);
	RunningTotal = RunningTotal.toFixed(2);
	
	$("#priceamt").text(RunningTotal);
}



// Colorbox Lightbox Inline Guide Code
$(document).ready(function(){	
	$("#showprices").colorbox({width:"80%", inline:true, href:"#pricing"});
});

//Colorbox Lightbox Photo Code
$(document).ready(function(){	
	$("a[rel='lightbox']").colorbox({transition:"fade"});
});

// Utility Functions
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return newnumber; // Output the result
}


////////////////////////////////// Google Maps Functions

//<![CDATA[

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        var marker = new GMarker(new GLatLng(45.591075,-94.166586));
        var html="<p><img src='img/maneas-header-sm.jpg'" +
         "width='150' height='19'/> <br/>" +
         "114 2nd Ave N <br> Sauk Rapids, MN</p>";
		
        
        map.setCenter(new GLatLng(45.591075,-94.166586), 14);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(html);
        map.setUIToDefault();
      }
    }
//]]>



////////////////////////////////////////// Feedback Form AJAX and Validation

    $(function() {  
		$('.error').hide();
		$("#submit_btn").click(function() { 
        // validate and process form here  		
		
			$('.error').hide();  
			var name = $("input#name").val();  
				if (name == "") {  
				$("label#name_error").show();  
				$("input#name").focus();  
			return false;  
			} 
		
			var email = $("input#email").val();  
				if (email == "") {  
				$("label#email_error").show();  
				$("input#email").focus();  
			return false;  
			} 

			var fb = $("textarea#feedback").val();  
				if (fb == "") {  
				$("label#feedback_error").show();  
				$("textarea#feedback").focus();  
			return false;  
			}
			
			var turing = $("input#turing").val();  
				if (turing == "" || turing != 5) {  
				$("label#turing_error").show();  
				$("input#turing").focus();  
			return false;  
			}
			
			$(this).after("<p style='color:red;'>Submitting Form...Please Wait.</p>");
			$(this).hide();

			var recipients = $("input#recipients").val();
			var subject = $("input#subject").val();


			var dataString = 'recipients=' + recipients + '&subject=' + subject +'&realname='+ name + '&email=' + email + '&feedback=' + fb;
			//alert (dataString);return false;  
				$.ajax({  
				type: "GET",  
				url: "http://www.maneasmeats.com/formmail.php",  
				data: dataString,  
				success: function() {  
					$('#feedbackform').html("<div id='message'></div>");  
					$('#message').html("<h2 style='color:red;'>Feedback Submitted!</h2>")  
					.append("<p>Thanks for telling us your opinions.</p>")  
					.hide()  
					.fadeIn(1500, function() {  
						$('#message');  
					});
				}
				});  
			return false;  			
      });  
    });  
























