// JavaScript Document
var $j = jQuery.noConflict();


/* ==== Auto Rell and Emails ==== */
function external_links()
{
 // turn rel="external" attributes into new window popups
 $j('a[rel^="external"]').click( function() {
  window.open( $j(this).attr('href') );
  return false;
 });
 // turn "external" classes into new window popups
 $j('a.external').click( function() {
  window.open( $j(this).attr('href') );
  return false;
 });
 // find all external links on a site and make new window popups
 $j("a[href^='http://']").not("a[href^='http://www.younggrasshopper.com']").not("a[href^='http://younggrasshopper.corecms.co.nz']").not("a[href^='https://younggrasshopper.worldsecuresystems.com']").not('a[rel^="external"]').click(function(){
  window.open(this.href,'external');
  return false;
 });
 // Email Converter
 $j('a.email').each(function(){
 	e = this.title.replace('+','@');
 	this.href=" ";
	this.href = 'mailto:' + e; $j(this).text(e);
 });
};


/* ==== Copy and paste details  ==== */
function copyPaste() { $j("input#paypalfirstname").val($j("input#Fullname").val()); $j("input#paypalemail").val($j("input#EmailAddress").val()); }

/* ==== COPY OTHER DETAILS  ==== */
function copyDetails() {	
	$j("input#FullName").blur( function () { copyPaste(); });
	$j("input#EmailAddress").blur( function () { copyPaste(); });
	$j("input#submitquestion").mouseover( function () { copyPaste(); });
	$j("input#EmailAddress").change( function () { copyPaste(); });
	$j("input#FullName").change( function () { copyPaste(); });	
}

/* Check if checkout has guidance question & not got phyiscal product */
function cartCycleCheck() {

	//live loop to not die on changes
	$j(".productitemcell").each(function(){
		if ( $j(this).text() =="gq" ) {
			console.log("Guidance Question found");
			$j("#shippingDetails").hide();
		}

	});
	
}

function regFormHideSHip() {


	cartURL = "https://younggrasshopper.worldsecuresystems.com/OrderRetrievev2.aspx"
	
	$j('#cartSumCheck').load('/OrderRetrievev2.aspx #cart', function() {
	
		$j(".productitemcell").each(function(){

			if ( $j(this).text() =="gq" ) {
				console.log("Guidance Question found");
			}
		});
	
	});
	
	
	// Look at content on checkout page
		// Do cart Cycle
		// If it meets requirements then hide shipping section

}


function jqsub()
{
	var $form = $j('#businessQuestionForm'); // set your form ID
	var $messagebox = $j('#message'); // set your message box ID
	var $successmessage = '<h3 class="successmessage">Thank You For Your Submission</h3><h4>Please Wait a Moment</h4><p>Your page will reload and will take you to <span class="pay">pay</span><span class="pal">pal</span> to make your payment.<br/><small>This may take a minute on slower connections. Please do not click anything until paypal loads thank You.</small></p>'; // replace with your own success message in HTML format
	var $errormessage = '<h3 class="errormessage">There was a problem, Please Try Again</h3>'; // replace with your own error message in HTML format
	
	$j.ajax(
	{
		type	: 'POST',
		url		: $form.attr('action'),
		data	: $form.serialize(), 
		success	: function (msg)
		{
			if (msg.charAt(0) === '{')
			{
				var foundErrors = false;
				try
				{
					eval('var o = ' + msg);
				}
				catch ( err )
				{
					var txt = "";
					txt = "Thank you for submitting your question. We have successfully received your question.\n\n";
					txt+= "However we were unable to redirect you to PayPal at this time. \n\n";
					//txt+= "Error description: " + err + "\n\n";
					txt+= "Please email hi@younggrasshopper.com to manually handle your payment method.\n\n";
					txt+= "Click OK to continue.\n\n";
					alert(txt);
					
					foundErrors = true;
				}
				
				if ( !foundErrors )
				{
					if (o.FormProcessV2Response.success) {
						$messagebox.append($successmessage) 
						$messagebox.fadeIn("fast");
						$j("#paypalform").submit();
					}
					else {
						$messagebox.append($errormessage) 
						$messagebox.fadeIn();	
					}
				}
				
			}
		},
		error: function (msg)
		{
			$messagebox.append($errormessage) 
			$messagebox.fadeIn();
		}
	});
}

function jqsub2()
{
	var $form = $j('#personalQuestionForm'); // set your form ID
	var $messagebox = $j('#message'); // set your message box ID
	var $successmessage = '<h3 class="successmessage">Thank You For Your Submission</h3><h4>Please wait a moment</h4><p>Your page will reload and will take you to <span class="pay">pay</span><span class="pal">pal</span> to make your payment.<br/><small>With some internet connections this may take a minute to load.</small></p>'; // replace with your own success message in HTML format
	var $errormessage = '<h3 class="errormessage">There was a problem, Please Try Again</h3>'; // replace with your own error message in HTML format
	
	$j.ajax(
	{
		type: 'POST',
		url: $form.attr('action'),
		data: $form.serialize(), 
		success: function (msg)
		{
			if (msg.charAt(0) === '{')
			{
				var foundErrors = false;
				try
				{
					eval('var o = ' + msg);
				}
				catch ( err )
				{
					var txt = "";
					txt = "Thank you for submitting your question. We have successfully received your question.\n\n";
					txt+= "However we were unable to redirect you to PayPal at this time. \n\n";
					//txt+= "Error description: " + err + "\n\n";
					txt+= "Please email hi@younggrasshopper.com to manually handle your payment method.\n\n";
					txt+= "Click OK to continue.\n\n";
					alert(txt);
					
					foundErrors = true;
				}
				
				if ( !foundErrors )
				{
					if (o.FormProcessV2Response.success) {
						$messagebox.append($successmessage) 
						$messagebox.fadeIn("fast");
						$j("#paypalform").submit();
					}
					else {
						$messagebox.append($errormessage) 
						$messagebox.fadeIn();	
					}
				}
			}
		},
		error: function (msg) {
			$messagebox.append($errormessage) 
			$messagebox.fadeIn();
		}
     });
}

//$j('#paypalform').submit();

/* ==== RELOAD THE CART ==== */
function reloadThis(actionID) {

	actionID.change(
		function()
		{
			top.location.reload();
		}
	);

}
function reloadThisClick(actionID) {

	actionID.click(
		function()
		{
			top.location.reload();
		}
	);

}

/* ==== GET URL VALUES ==== */
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/* ==== GET PAYPAL URL DETAILS ==== */
function displayPaymentDetails() {
	getUrlVars();
	var transactionID  = getUrlVars()["tx"];
	var amount = getUrlVars()["amt"];
	var currency = getUrlVars()["cc"];
	var displayMe = '<div class="trans-id">Your Transaction ID: <strong>' + transactionID + '</strong></div>' + '<div class="amount">Amount Paid: <strong>' + amount + ' ' + currency + '</strong></div>';
	return displayMe;
}

/* ==== CREATE GUIDANCE PAYMENT ==== */
function submitPayment() {
	if ( $j("#question-field") != '') { 
		$j("#paypalform").submit();
	}
}

/* ==== SUBMIT FORM ==== */
function submitme() {
		j(".submitme").submit();
}

/* ==== SHOW FIELDS IF OPTION TICKED ==== */
function showFriends() {
	if ( $j("input[@name='friend']:checked").val() == "Yes" ) {
		//$j("div.tell-a-friend").show();
		$j("#tellafriend").removeClass("hidden");
	}
	if ( $j("input[@name='friend']:checked").val() == "No" ) {
		//$j("div.tell-a-friend").show();
		$j("#tellafriend").addClass("hidden");
	}
	
	$j("#friend_0").change(function()
	{
		if ( $j(this).val() == "Yes" ) {
			$j("#tellafriend").removeClass("hidden");
		}
	});
	$j("#friend_1").change(function()
	{
		if ( $j(this).val() == "No" ) {
			$j("#tellafriend").addClass("hidden");
		}
	});
	
}

/* ==== COPY ADDRESS WHEN SELECTED ==== */
function copyAddress()
{
	if ($j("input#ShippingAddress").val() == "") {
		$j("input#ShippingAddress").val($j("input#BillingAddress").val()); 
	}
	if ($j("input#ShippingCity").val() == "") {
		$j("input#ShippingCity").val($j("input#BillingCity").val());
	}
	if ($j("input#ShippingState").val() == "") {
		$j("input#ShippingState").val($j("input#BillingState").val());
	}
	if ($j("input#ShippingZip").val() == "") {
		$j("input#ShippingZip").val($j("input#BillingZip").val());
	}
		var billIndex = $j("#BillingCountry option").index($j("#BillingCountry option:selected"))
		$j("#ShippingCountry option:eq("+billIndex+")").attr("selected", "selected")
}

/* ==== EDIT FIELDS IF CHANGED ==== */
function editifchanged() {
	$j("input#BillingAddress").change(function()
	{
		var vamount = $j(this).val();
		$j("input#ShippingAddress").val(vamount);
	});
	$j("input#BillingCity").change(function()
	{
		var vamount = $j(this).val();
		$j("input#ShippingCity").val(vamount);
	});
	$j("input#BillingState").change(function()
	{
		var vamount = $j(this).val();
		$j("input#ShippingState").val(vamount);
	});
	$j("input#BillingZip").change(function()
	{
		var vamount = $j(this).val();
		$j("input#ShippingZip").val(vamount);
	});
	$j("input#BillingCountry").change(function()
	{
		var billIndex = $j("#BillingCountry option").index($j("#BillingCountry option:selected"))
		$j("#ShippingCountry option:eq("+billIndex+")").attr("selected", "selected")
	});

}
/* ==== UPDATE WHEN TOLD ==== */
function updateWhenTold() {

		var vamount = $j("input#BillingAddress").val();
		$j("input#ShippingAddress").val(vamount);

		var vamount = $j("input#BillingCity").val();
		$j("input#ShippingCity").val(vamount);

		var vamount = $j("input#BillingState").val();
		$j("input#ShippingState").val(vamount);

		var vamount = $j("input#BillingZip").val();
		$j("input#ShippingZip").val(vamount);
		
		var billIndex = $j("#BillingCountry option").index($j("#BillingCountry option:selected"));
		$j("#ShippingCountry option:eq("+billIndex+")").attr("selected", "selected");

}
/* ==== ANOTHER UPDATE 100% CHECK  ==== */
function updateFields()
{	
	editifchanged()
	$j("input#BillingAddress").blur( function () { editifchanged(); updateWhenTold(); }); 
	$j("input#BillingCity").blur( function () { editifchanged(); updateWhenTold(); });
	$j("input#BillingState").blur( function () { editifchanged(); updateWhenTold(); });
	$j("input#BillingZip").blur( function () { editifchanged(); updateWhenTold(); });
	$j("input#BillingCountry").blur( function () { editifchanged(); updateWhenTold(); });
	$j("input#BillingCountry").click( function () { editifchanged(); updateWhenTold(); });

}
/* ==== CLEAR ADDRESS FIELDS ==== */
function removeAddress() {
	$j("input#ShippingAddress").val("");
	$j("input#ShippingCity").val("");
	$j("input#ShippingState").val("");
	$j("input#ShippingZip").val("");
}

/* ==== BILLING THE SAME AS SHIPPING ==== */
function billToShip()
{
	if ( $j("input[@name='biltoship']:checked").val() == "Yes" ) {
		copyAddress();
		$j("#entertext").addClass("hidden");
		$j("#shippingDetails").hide();	
	}
	if ( $j("input[@name='biltoship']:checked").val() == "No" ) {
		$j("#entertext").removeClass("hidden");
		$j("#shippingDetails").show();	
		removeAddress();
	}
	
	$j("#bilship_0").change(function()
	{
		if ( $j(this).val() == "Yes" ) {
			copyAddress();
			$j("#entertext").addClass("hidden");
          $j("#shippingDetails").hide();
		}
	});
	$j("#billship_1").change(function()
	{
		if ( $j(this).val() == "No" ) {
			removeAddress();
			$j("#entertext").removeClass("hidden");
          $j("#shippingDetails").show();
		}
	});

}
/* ==== SUBMIT FORM ==== */
function submitPayment() {
		$j("#paypalform").submit();
}


/* =========== DOM MAIN LOAD =========== */
$j(document).ready(function()
{

	external_links();
	updateFields();
	copyDetails();
		
	if ( $j('#catCartDetails') ) {
		reloadThis( $j("select#ShippingOptions") );
		reloadThis( $j(".cartInputText") );
	}
	
	if ( $j('#ask-a-question').length ){
		$j('#ask-a-question textarea').limit('1024','#charsLeft');

	}
	
	
	if ( $j('.podcasts') ) {
		reloadThisClick( $j(".cart-options .btn") );
	}
	
	if ($j('#catwebformbutton')) {
		$j("#catwebformbutton").mouseover( function () { updateWhenTold(); }); 
	}
	
	if ($j('#checkout')) {
		billToShip();
		regFormHideSHip();
	}
	
	if ( $j("#cart").length ) {
		cartCycleCheck();
	}
	
	if ($j('#payment')) {
		getUrlVars();
		var processStatus = getUrlVars()["st"];
		var fullDetails = displayPaymentDetails();
		$j("#pay-satus").append( processStatus );
		$j("#payment-details").append( fullDetails );

	}
	
	if ( $j('#form-contact') ) {
		showFriends();
	}
	
	// Clear Search Field
	$j('#topic_suggestion').mouseover (function()
	{
		if (this.value=='Your suggested topic...') { this.value='';return true;}
	});
	$j('#topic_suggestion').mouseout (function()
	{
		if (this.value=='') { this.value='Your suggested topic...';return true;}
	});
	
	if ($j("#podcasts-test")) {
		$j("#podcasts-test").load("/hot-podcasts");
	}
	
	if ( $j(".product-image") ) {
		$j(".product-image a").replaceWith('<span><img alt="Young Grasshopper 2GB MP3 Player" src="/images/products/2gb-mp3-player-trans.png" id="catsproduct_834763"></span>');
	
	}

});

