/*
	// ------------------------------------------------------------------------------
	// CLASS:
	// DS2.Coupons.js.coupons
	//
	// PURPOSE:
	// I am the primary JS file for coupon structure
	//
	// COPYRIGHT:
	// Copyright (c) 2008 Dealerskins, Inc. All Rights Reserved.
	//
	// REVISION HISTORY:
	//
	// ******************************************************************************
	// User: ADM  Date: 7/18/2008
	// Initial creation
	// ******************************************************************************
	// ------------------------------------------------------------------------------
*/

$(document).ready(function(){

	// for some reason this container is 2 pixels narrower in Firefox. Let's fix that
	if ($.browser.msie) {
		$('#contentBody').css('width','590px');
	}

	// drop in the tops and bottoms of the coupon container, and header
	$('#headerBody, #contentBody')
		.before('<div class="short"></div>')
		.before('<div class="medium"></div>')
		.after('<div class="short"></div>')
		.after('<div class="medium"></div>');

	// the focus / blur functionality of the text input
	// fields for the email a friend form.
	$('#emailToFriend input.email').bind('focus', function() {
		// Set the default value if it isn't set
		if ( !this.defaultValue ) this.defaultValue = this.value;
		// Check to see if the value is different
		if ( this.defaultValue && this.defaultValue != this.value ) return;
		// It isn't, so remove the text from the input
		this.value = '';
	})
	.bind('blur', function() {
		// If the value is blank, return it to the defaultValue
		if ( this.value.match(/^\s*$/) )
			this.value = this.defaultValue;
	});




	// ajax calls for the "additional coupons" links underneath the primary coupon display
	$('#couponAdditional a').click(function(e){
		// prevent the default behaviour of the link, because "return false" is inelegant
		e.preventDefault();
		// shortcut for "this" link
		var $link = $(this);
		// get a shortcut for the parent li
		var $container = $(this).parent('li');
		// shortcut for the image
		var $img = $('#contentImg img');
		// replace the current image with a clear gif
		$img.css('visibility','hidden');
		// get the coupon id of the current clicked link
		var couponid = $link.attr('href').match(/[0-9]+$/gi)[0];
		// get the siteid
		var siteid = $('#siteid').val();
		// get the uid
		var uid = $('#uid').val();
		// get the ssid
		var ssid = $('#ssid').val();
		// set up the loading background
		$container.css({
			'background-image': 'url(/coupons/images/ajax-loader1.gif)'
		});
		// make an ajax call to get the data for the selected coupon
		$.getJSON("/AjaxService/coupons/coupons.cfc?method=getSingleCoupon", {
			couponid: couponid,
			siteid: siteid,
			uid: uid,
			ssid: ssid,
			returnFormat:'JSON'
		},function(d){
			// ColdFusion returns JSON as a string, so we have to evaluate it before using it
			// here we're accessing the nested array so that we don't have to specify anything
			// more than just simple indexes
			var o = d['DATA'][0];

			// dump all the values into their respective containers
			$('#titlePretext').html(o[2]);
			$('#titleText').html(o[1]);
			$('#titlePosttext').html(o[3]);
			$('#couponText').html(o[4]);
			$('#disclaimer').html(o[5]);
			$('#pricePretext').html(o[6]);
			$('#priceText').html(o[7]);
			$('#pricePosttext').html(o[8]);
			$('#expiration').html(o[9]);
			// update coupon id form field
			$('#couponid').val(couponid);
			
			// temp var for the filename
			var filename = o[13];
			// now write the image path, and the new img filename into the src attribute of the image
			// but only if it's not the default "select image" image, or an empty string
			if (filename.indexOf('display_default') > 0) {
				// if we don't want to show the image associated with this coupon
				$img.attr('src',filename).css('visibility','hidden');
			} else {
				// we do want to show the image again
				$img.attr('src',filename).load(function() {
					$(this).css('visibility','visible');
				});
			}

			// finally, get rid of the background for the LI tag
			$container.css({
				'background-image': 'none'
			});
		});
	});



	$('.printForm').click(function(e){
		// prevent the default behaviour of the link, because "return false" is inelegant
		e.preventDefault();

		// get the siteid
		var siteid = parseInt( $('#siteid').val() );
		// get the coupon id of the current clicked link
		var couponid = parseInt( $('#couponid').val() );
		// get the uid
		var uid = $('#uid').val();
		// get the ssid
		var ssid = $('#ssid').val();
		//only insert the stat if siteid and couponid are both legit numbers
		if (!isNaN(siteid) && siteid!= 0 && !isNaN(couponid) && couponid!= 0) {
			// if the msg var has NO values, then it's time to make the AJAX call to send the email
			$.get("/AjaxService/coupons/coupons.cfc?method=insertStat", {
				siteid: siteid,
				couponid: couponid,
				StatsPageTypeID: 11,
				type: 'print',
				uid: uid,
				ssid: ssid
			});
		}

		// fire the print functionality
		window.print();
	});




	// setting up the email a friend functionality...again (sigh)
	$('#emailToFriend').submit(function(e){
		// prevent the default behaviour of the link, because "return false" is inelegant
		e.preventDefault();

		// temp msg variable
		var msg = [];

		// the email regular expression
		var re = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;

		// get both email address fields
		var $yEmailField = $('#youremail');
		var $fEmailField = $('#friendemail');

		// and their current values
		var youVal = $yEmailField.val();
		var friendVal = $fEmailField.val();

		// test to see if they're valid email addresses
		var youTest = re.test(youVal);
		var friendTest = re.test(friendVal);

		// create messages for missing, or invalid, email addresses
		// "yours"
		if (youVal == '' || youVal == "Your email") {
			// email is missing
			msg.push(' Please enter your email address');
		} else {
			// email is invalid
			!youTest ? msg.push(' Your email address appears to be invalid') : '';
		}
		// "your friends"
		if (friendVal == '' || friendVal == "Your friend's email") {
			// email is missing
			msg.push(" Please enter your friend's email address");
		} else {
			// email is invalid
			!friendTest ? msg.push(" Your friend's email address appears to be invalid") : '';
		}

		// test the length of the msg array
		if (msg.length) {
			// if the msg var has values, we need to display them
			// write any msg into the msg container
			// insert the msg
			insertMsg('error',msg);
			// move the container
			animateContainer('u');
			// attach a click handler to the image inside the message container
			attachClicks();
		} else {
			// get the coupon id of the current clicked link
			var couponid = $('#couponid').val();
			// get the siteid
			var siteid = $('#siteid').val();
			// get the pageid
			var pageid = $('#pageid').val();
			// get the uid
			var uid = $('#uid').val();
			// get the ssid
			var ssid = $('#ssid').val();
			// get the site url
			var siteURL = $('#siteURL').val();
			// if the msg var has NO values, then it's time to make the AJAX call to send the email
			$.getJSON("/AjaxService/coupons/coupons.cfc?method=sendEmail", {
				couponid: couponid,
				siteid: siteid,
				pageid: pageid,
				uid: uid,
				ssid: ssid,
				yourEmail: youVal,
				friendEmail: friendVal,
				siteURL: siteURL,
				returnFormat:'JSON'
			},function(d){
				// reset the "friend's email" form field
				$fEmailField.val("Your friend's email");
				// insert the msg
				insertMsg('success',d);
				// move the container
				animateContainer('u');
				// attach a click handler to the image inside the message container
				attachClicks();
				// then scroll the window back after 3 seconds
				setTimeout(function() {
					animateContainer('d');
				}, 3000);
			});
		}

	});

	function insertMsg(type,msg) { // values for type are 'error', or 'success'
		// error, and success, images for the animation area
		var errorImg = '<img src="/coupons/images/cancel.png" width="16" height="18" alt="Back to the form" />';
		var successImg = '<img src="/coupons/images/save.png" width="16" height="18" alt="Back to the form" />';
		var img = eval(type+'Img');
		$('#emailMsg').html(img + msg);
	}

	function attachClicks() {
		$("#emailMsg img").click(function(){
			animateContainer('d');
		});
	}

	function animateContainer(dir) {
		var amt = (dir == 'u') ? '-22px' : '0px';
		$("#emailForm, #emailMsg").animate({
			top: amt
		}, 250);
	}

});
