/**
 * @author Touchnote
 *  - requires jQuery +1.3
 *  - This JS should remain non initialised,
 *  - it is intended to be used by specific postcard landing pages
 *   * sets events for common page elements
 *   * provides validation tools
 *   * registers common vars for config (overridable)
 */		

// Some globals
var imguuid; 
var disableRedirect = true;
var autoRedirect = false;
var load_interval;
var isValidating = false;
var currentAddressIsValid = false;

// Google event tracking
var ga_pgCategory = "Partner_Postcard_Landing";
function ga_trackEvent(cat,act,lab){
	pageTracker._trackEvent(cat, act, lab);
}


// Address Line Validation 
function validateAddressLine(rule, field, vMssg){
	if(!rule){ // failed validation
		vMssg = "<div class='addressvalidation'>"+vMssg+"</div>";
		if($('#Address'+field).next().attr('class') == 'addressvalidation'){
			$('#Address'+field).next().replaceWith(vMssg);
		}else{
			$('#Address'+field).after(vMssg);
		}
		return false;
	}else{
		// remove the validation message if it exists
		if($('#Address'+field).next().attr('class') == 'addressvalidation'){$('#Address'+field).next().remove();}
		return true;
	}
}

//Validate whole form
function validateAddressForm() {

	// seems like this can  be a little slow so we lock it while in progress so as to not conflict
	if(!isValidating){
		isValidating = true; // lock
	
		validAddress = true;
		lineContentCounter = 0;
		$.each(['Name', 'Line1', 'Line2', 'Line3', 'Town', 'CountyState', 'Postcode', 'CountryId'], function(i, field){
			lineElem = $('#Address'+field);
			linevalue= lineElem.val();
			
			//validation
			switch(field){
	    		case 'Name': {
	        		if(!validateAddressLine((linevalue.length > 0 && linevalue.length <= lineElem.attr('maxlength')), field, "Please supply a name between 1-"+lineElem.attr('maxlength')+" characters long")){ 
	        			validAddress = false; 
	        		}
	    		}; break;
	    		case 'Line1': {
	        		if(!validateAddressLine((linevalue.length > 0 && linevalue.length <= lineElem.attr('maxlength')), field, "Please supply first line of the address")){ 
	        			validAddress = false; 
	        		}
	    		}; break;
	    		case 'Town': {
	        		if(!validateAddressLine((linevalue.length > 0 && linevalue.length <= lineElem.attr('maxlength')), field, "Please supply a valid town")){ 
	        			validAddress = false; 
	        		}
	        		
	    		}; break;
	    		case 'CountryId': {
	        		if(!validateAddressLine((linevalue != 0), field, "Please select a country")){ 
	        			validAddress = false; 
	        		}
	        		
	    		}; break;
			}
	
			
			$('#hAddr'+field).val(linevalue);
			if(field == 'CountryId'){
				linevalue = $('#Address'+field+' :selected').text();
			}else{
	    		lineContentCounter += linevalue.length;
	    	}
			$('#Addr'+field).text(linevalue);
		}); // end field loop
		
		// we need to know if the lines are there 
		if(lineContentCounter > 0){$('#addressLines').removeClass('lined');}
		 
		// Valid addresses
		if(validAddress){
		
			currentAddressIsValid = true;
		
			$('.addressvalidation').empty();
			
			$('#addressForm').dialog('close');
			$('.ui-widget-overlay').hide();
			
		}else{
		
			currentAddressIsValid = false;
			$('#permAddress div.addressvalidation').html('There are error(s) with this address');
		}
		
		isValidating = false; // release
	}else{
		return setTimeout(validateAddressForm(), 500); // wait half a tick and go again
	}

	return false;
}


// Enable / Disable the Submit button
//
function activeSubmitButton(enable){

	if($.browser == 'msie'){
		if(enable){
			$("#sendPcForm").attr('src') = '/img/landing/postcard/paynow_ntp.png';
			$("#sendPcForm").show();
		}else{
			$("#sendPcForm").hide();
		}
	}else{
		if(enable){ 
			speed = 1000; buttVisibility = 1; 
			// whats the damage	
			wsPort = (($('#hotPreview').attr('width')/$('#hotPreview').attr('height')) < 1)?1:0;
			$('#wsPort').val(wsPort);
		}else{ 
			$("#sendPcForm").show(); // it's initially display:none for ie: hack :-(
			speed = 1; buttVisibility = 0.5; 
		}
		var isSubmitting = false;
		// handle validation before form submission
		$("#sendPcForm").fadeTo(speed, buttVisibility).unbind().click(function(e){ 
			if(!enable || isSubmitting){		
				// let google know
				ga_trackEvent(ga_pgCategory, "inactive_paynow",  "Clicked Pay Now button before it was ready.");
			}else{
			
				// check to see if the address has been filled in 
				if(!currentAddressIsValid){
					e.preventDefault();
					// flip the postcard
					if($('#flipbox').data('from').get(0).id == 'flipfront'){ // On the front, do a flip
						$('.flipcontrol').click();
						delay = 1500; // 1.5 seconds for the flip to do its thing please
					}else{
						delay = 10; // basically now 
					}
					// open the address dialogue
					setTimeout(function(){
						$('#addressLines').click(); 
						$('#addressForm').find('table').before('<div id="tmpMessage" style="clear:both;font-size: 14px; color:#f00">Please enter an address for the postcard</div>').prev().hide();
						$('#tmpMessage').fadeIn('slow');
						setTimeout(function(){
							$('#tmpMessage').fadeOut('slow').remove();
						}, 5000);
					}, delay);
					return false;
				}
			}
			if(enable){ // this will protect against secondary clicks causing double basket cards
				isSubmitting = true;  // sets the button to disabled after the click event
				enable = false;
				return true;
			}else{
				return false; 
			}
		});
	}
}

// see if the main image is loaded
// - if so get a bit excited
// 
function checkimageLoaded(){
	if($('#usersImage').attr('src') != '/img/spinner.gif'){ // loaded
		load_interval=window.clearInterval(load_interval);
		
		// activate the submission form
		activeSubmitButton(true);
		
		// show the preview link
		$('#previewImageLink').show();
		// hide the loader
		$('#hotPreview').fadeTo(1000, 1);
		$('#previewspinner').hide();
		if(autoRedirect){alert('redirecting..');}
	}
}

function setUUIDfromPath(path){
	// set the uuid from local filepath
	$('#imageref').attr('value', path.substr(path.lastIndexOf('/')+1, 36));
}

// Takes an image and creates a postcard thumbnail
// 
function postcardTnailPath(originalPath, previewWidthStrap){
	// Preview dims (defaults)
	var ptOpts_w = 1629;
	var ptOpts_h = 1161;
	
	hAdjust = ptOpts_w / ptOpts_h;
	ptOpts_w = Math.round(previewWidthStrap); 
	ptOpts_h = Math.round(previewWidthStrap / hAdjust); 
	previewOverlayOpts = '&fltr[]=postcard_overlay';
	return '/images/prod_rot_thumb/?src=' + originalPath + '&w='+ptOpts_w+'&h='+ptOpts_h+'&zc=1' + previewOverlayOpts;
	
}

// OnLoad
var clickTaleDummyImage = '/img/test.jpg'; // persistant test image
$(document).ready(function(){
	
	// Pass all relevant clicks back to clicktale
	//
	$('#flipit, #sendPcForm, #addressLines, #PersonalizedProductMessage').attach(ClickTalePlayback); // pass all relevant clicks back to clicktale
	
	// Address Form popup
	//
    $('#addressForm').dialog({ width: 560,height: 355,bgiframe: true,autoOpen: false,closeOnEscape: true,hide: 'slide',show: 'slide',resizable: false,modal: true});

    var validAddress = true;
    $('#saveAddress').click(function() {
		validateAddressForm();
		return false;
	}); // end saveAddress click event

    // Edit address button
    //
	$('#editAddress')
		.click(function(){ 
			// let google know
			ga_trackEvent(ga_pgCategory, "Open_Address_Dialog",  "clicked edit address in ththis streamline landing page");
			
			// open the dialogue
			$('#addressForm').dialog('open'); return false; 
		})
		.hover(		function(){ $(this).addClass("ui-state-hover");},function(){$(this).removeClass("ui-state-hover");})
		.mousedown(	function(){ $(this).addClass("ui-state-active");})
		.mouseup(	function(){ $(this).removeClass("ui-state-active");}
	);
	
	$('#addressLines').click(function(){ 
		
		// let google know
		ga_trackEvent(ga_pgCategory, "Open_Address_Dialog",  "clicked Address lines in ththis streamline landing page");
		
		// open the dialogue
		$('#addressForm').dialog('open'); return false; 
		
	});	
	
	
	// mode
	if(uiMode == 'flip'){
		$('#PersonalizedProductMessage').focus(function(el){$(el.originalEvent.target).css('border','2px dashed #333');}).blur(function(el){$(el.originalEvent.target).css('border','0px');})	
	}
	// - Clicking this button is basically irrelevant, it's mainly for user perception. 
	$('#personaliseLinkImage, #personaliseLink').click(function(){
		$(this).attr('src', '/img/tnthis/photofunia/btn-send-card-off.png');												
		return false;	
	});		

});