$(document).ready(function(){
	
	var urlStr = this.location.toString();
	var isSavings = urlStr.match( /savingscalculator/ );
	
	if(!isSavings)
	{
		isSavings = urlStr.match( /results/ );	
	}
	if(!isSavings){
	// price controls
	$("#calc-price-slider-range").slider({
		range: false,
		min: 0,
		max: 200,
		step: 5,
		values: [100],
		slide: function(event, ui) {
			$("#calc-price").val(ui.values[0]);
			$("#calc-current-price").html('$' + ui.values[0]);

			$("#calc-minutes").val(ui.values[0]);

			var mid = $("#calc-myprice-indicator").width() / 2 - 7;
			$("#calc-myprice-indicator").css({'position':'absolute', 'left' : ((($(this).children('.ui-slider-handle').position().left ) + $(this).position().left) - mid) + 'px',
				'top' : ($(this).position().top - 16)  + 'px'});
			$("#calc-myprice-indicator").show();			
			$("#calc-myprice-indicator").html(ui.values[0]);
			
		},
		stop: function(event, ui) {
		  $("#calc-myprice-indicator").hide();
		  $('#calc-form-filter').submit();
		}
	});

	$("#calc-price").val($("#calc-price-slider-range").slider("values", 0));
	$("#calc-price-text").html('$' + $("#calc-price-slider-range").slider("values", 0));

	// minutes controls
	$("#calc-minutes-slider-range").slider({
		range: false,
		min: 0,
		max: 5100,
		values: [600],
		step: 100,
		slide: function(event, ui) {
		
		if(ui.values[0] == 5100)
		{ 
			$("#calc-minutes").val('UNLIMITED'); //need?
			$("#calc-minutes-2").val('UNLIMITED');
			$("#calc-current-minutes").html('UNLIMITED');
			$("#calc-current-minutes p").html('UNLIMITED');
			$("#calc-minutes-indicator").html('UNLIMITED');
		}
		else
		{
			$("#calc-minutes").val(ui.values[0]);
			$("#calc-minutes-2").val(ui.values[0]);
			$("#calc-current-minutes").html(ui.values[0] + 'min');
			$("#calc-current-minutes p").html(ui.values[0] + 'min');
			$("#calc-minutes-indicator").html(ui.values[0]);
		}
			
			var mid = $("#calc-minutes-indicator").width() / 2 - 7;
			$("#calc-minutes-indicator").css({'position':'absolute', 'left' :((($(this).children('.ui-slider-handle').position().left ) + $(this).position().left) - mid) + 'px',
				'top' : ($(this).position().top - 10)  + 'px'});
			$("#calc-minutes-indicator").show();			
			//$("#calc-minutes-indicator").html(ui.values[0]);
		},
		stop: function(event, ui) {
		  $("#calc-minutes-indicator").hide();
		  $('#calc-form-filter').submit();
		}
	});

	$("#calc-minutes").val($("#calc-minutes-slider-range").slider("values", 0));
	$("#calc-minutes-2").val($("#calc-minutes-slider-range").slider("values", 0));
	$("#calc-minutes-text").html('$' + $("#calc-minutes-slider-range").slider("values", 0));
	
	// messages controls
	$("#calc-messages-slider-range").slider({
		range: false,
		min: 0,
		max: 5050,
		step: 50,
		values: [5050],
		slide: function(event, ui) {
			
			if(ui.values[0] == 5050)
			{
			   $("#calc-current-messages").html('UNLIMITED');
			   $("#calc-messages-2").val('UNLIMITED');
			   $("#calc-mymessages-indicator").html('UNLIMITED');
			}
			else
			{
				$("#calc-current-messages").html(ui.values[0]);
				$("#calc-messages").val(ui.values[0]);
				$("#calc-messages-2").val(ui.values[0]);

				//floating div
				$("#calc-mymessages-indicator").html(ui.values[0]);
			}


			var mid = $("#calc-mymessages-indicator").width() / 2 - 7;
			$("#calc-mymessages-indicator").css({'position':'absolute', 'left' : ((($(this).children('.ui-slider-handle').position().left ) + $(this).position().left) - mid) + 'px',
				'top' : ($(this).position().top - 10)  + 'px'});
			$("#calc-mymessages-indicator").show();			
		},
		stop: function(event, ui) {
		  $("#calc-mymessages-indicator").hide();
		  $('#calc-form-filter').submit();
		}
	});
	$("#calc-messages-2").val('UNLIMITED');
	$("#calc-messages").val($("#calc-messages-slider-range").slider("values", 0));
	$("#calc-messages-text").html('$' + $("#calc-messages-slider-range").slider("values", 0));
	
	}
	
	//includes controls	
	$('.toggle').toggle(  
       function(){ // you can add as much here as you'd like
    	   var currentId = $(this).attr('id');
            $('#'+currentId+'-img').attr('src','/images/calculator/'+currentId+'-selected.png');
            $('#'+currentId+'-input').attr('checked',true);
            
       }, function() { // same here
    	   var currentId = $(this).attr('id');  

            $('#'+currentId+'-img').attr('src','/images/calculator/'+currentId+'.png');
            $('#'+currentId+'-input').attr('checked',false);
            
       });
	
	$('#calc-featurebuttons input').each(function(n,item){
		if($(this).attr('checked'))
		{ 
			var thename = $(this).attr('id');
			thename = thename.replace('-input', '');
			$('#'+ thename +'-img').attr('src','/images/calculator/'+ thename +'-selected.png');
			$('#' + thename).click();
		}
	});

//	$('#savings-calc-form').submit(function(){
//		alert('cool');
//	});
	
//	//Popup Calculator Results.
//	$('#savings-calc-form').ajaxForm({
//		success: function(data) {
//			$('#lightbox-container').addClass( 'popup-savings-calculator' );
//			$('#lightbox-container-content').html(data);
//			$('#lightbox-container').jqmShow(); 
//		}
//	});
	$('.jqmClose').click(function(){
	if(clonedTell)
	{
		$('#tell-a-friend-content').html(clonedTell.html());
	}
//		$('#printcontent').hide();
	});
	
	
	
//////////##################
	
	 $('a.plan-price-link').click(function(event){
			event.preventDefault();
			 
			 $.ajax({ 
				 dataType: 'json',
				 type: 'post',
				 //url: '/dev.php/default/retrievePlanpricing', 
				 url: '/savingscalculator/retrievePlanpricing',
				 data: ({seo : this.getAttribute('name'), current_price: $('#user-price').val(), 
					 	suggested_price: $('#suggested-price').val()}), 
				 success: function(response){
				 //$('#heading-1').html(response.yousave);
				 $('#suggested-plan').animate({ "width": "toggle", "opacity": "toggle"},"slow", function(){
					 
					var plus = "<div><h3>PLUS:</h3>";
					plus += "<div>No Signed Contracts</div><div>No Credit Checks</div><div>No Overages</div><div>No Surprise Bills</div></div>";
					 
					 $('#suggested-plan').html(response.message + plus ).animate({ "width": "toggle", "opacity": "toggle"},"slow") ;
					 
				 });
				 
				 if(response.animateheader)
				 {	 
					 $('#heading-you-could').animate({"opacity": "toggle"},"slow", function(){
						 //$('#heading-you-could').text(decoded)
						 $('#heading-you-could').html(response.yousave)
						 .animate({  "opacity": "toggle"},"slow")				 
					 }) ;
				 }

				 //'add plan to cart' button new selection
				 $('.plan-button').hide();
				 $('.plan-button-' + response.newprice).show();
				 
		      }
		      	
		      }); //ajax

			 //active state
			 	$('a.plan-price-link').removeClass('current');		
			 	$(this).addClass('current');
		 });
		 

	 var clonedTell;	 
			$('#tell_link').click(function(){
				//$('.tell-a-friend').click(function(){
					$('#lightbox-container').addClass( 'popup-savings-calculator' );
//					//alert($('#tell-a-friend-content'));
					var tell = $('#tell-a-friend-content');
					//$('#tell-a-friend-content').html('');
					clonedTell = tell.clone();
					tell.html('');
					$('#lightbox-container-content').html(clonedTell.html());
					$('#lightbox-container').jqmShow(); 
					
				});	 
	

			//$('#change-shop-zip').click();
			//$('#change-shop-zip').trigger('click');
		$('#savings-calculator-change-zip').click(function (event) {
				event.preventDefault();
				$.get(this.href, function(data) {
					popupZipFormSavings(data, '');
				});			
		});	
		
		function popupZipFormSavings(zipformcontent, successurl) {
			$('#lightbox-container-content').html(zipformcontent);
			$('#lightbox-container').addClass( 'popup-zipcode' );

			$('#form-zipentry').ajaxForm(
					{
						dataType: 'json',
						beforeSubmit: function(formData, jqForm, options) {
							if (ajaxBlocked($(jqForm).find('button'))) return false;
						},
						success: function(data) {
							if (data.islocationset) {
								if (successurl != '') {
									document.location = successurl;
								} else {
									//Success url is empty. So refresh the
									//document.location = document.location;
									$('#savings-calculator-hidden').submit();
								}
							} else {
								ajaxUnblock();
								$('#zipformerror').fadeOut('normal', function() {
									$('#form-zipentry').addClass( 'popup-zipcode-error' );
									$('#zipformerror').html(data.message);
									$('#zipformerror').fadeIn();
								});

								hbxFailedZip(this.data, 'zipsearch_shop_failed');
							}
						}

					}
				);

		  $('#lightbox-container').jqmShow();
		}		
		
//////////##################	
	
});

function tellFriend() {
//	$('#savings-calculator-content').hide("normal");
//	$('#tell-a-friend-content').show("normal");
}
function closeTellFriend(event) {
	//make sure these two lines don't fail
	$('#tell-a-friend-content').hide("normal");
	$('#savings-calculator-content').show("normal");
	if(event !== undefined) {
		event.preventDefault();
	}
	
	$('.jqmClose').click();
}

function printThis() {
//USING FIX BELOW	
//	// PRINT FUNCTION DOESN'T INCLUDE POPUP SO APPEND POPUP CONTENT TO PARENT
//	var popupContent = $('#lightbox-container-content').html();
//	$('#content').append('<div id="printcontent">'+popupContent+'</div>');
	//window.print();
	//fix the print css
//	var popupContent = $('#lightbox-container-content').html();
//	
//	$('.jqmClose').trigger("click");
//
//	printablePopupWindow(popupContent);
	
	
	//rework
	
	var clone = $('#savings-calculator-content').clone();
	var logo = "<img src=\"/images/print/logo-print.png\" alt=\"Cricket\"/>";
	clone.prepend(logo);
	clone.children('.save-heading').append("<br/>");
	clone.children().children('#available-plans').remove();
	clone.children().children('#suggested-plan').children('.price-tag').html('<img src="/images/calculator/calc-icons-best-deal.png"/>');
	//clone.children().children('#suggested-plan').children('.price-tag').attr('margin-right', '-10px;');
	clone.jqprint();	
	//printablePopupWindow(clone.html());
	
}

//popup
function printablePopupWindow(popupContent)
{
	var myWin = window.open("", "","toolbar=0,menubar=0,location=0,resizable=1,status=0,scrollbars=0,width=750,height=680");
	
	var screenW = 640, screenH = 480;
	if (parseInt(navigator.appVersion)>3) {
	 screenW = screen.width;
	 screenH = screen.height;
	}
	else if (navigator.appName == "Netscape" 
	    && parseInt(navigator.appVersion)==3
	    && navigator.javaEnabled()
	   ) 
	{
	 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
	 var jScreenSize = jToolkit.getScreenSize();
	 screenW = jScreenSize.width;
	 screenH = jScreenSize.height;
	}
	myWin.moveTo((screenW / 2) - (750)/2,(screenH / 2) - (480)/2);
	
	myWin.document.write("<html><head>" 
			+
	"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/layout.css\" />" +
	"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/typography.css\" />" +
	"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/utility.css\" />" +
    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/popup.css\" />" +
    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/buttons.css\" />" +
	"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/savings-calculator.css\" />" +		

    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/minicart.css\" /> " +
    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/forms.css\" />" +
    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/glossary.css\" />" +
    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/processflow.css\" />" +
    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/item.css\" />" +
    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/tabs.css\" />" +
//    "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"/css/print.css\" />" +
    
    "<style>#bottom-links{display:none;}#lightbox-container-content{padding: 10px;}</style>" +
    "<title>cricket savings calculator</title>" + 
	"</head>" +
	"<body>");
	//myWin.document.write("<div id=\"print-header\" ><img src=\"images/print/logo-print.png\" alt=\"Cricket\"/></div>");
	myWin.document.write(popupContent);
	//myWin.document.write ('<div><a href="#" onclick="javascript:window.close();">Close this window</a></div>');	
	myWin.document.write("</body></html>");
	myWin.document.title = "Savings Comparison";

	
	if(navigator.appName == "Netscape")
	{
	//	myWin.print();
	}else
	{
		//ie
	//	myWin.document.execCommand('print', false, null);
	}
}

/////////////////////////////////
var submitTellafriendBlock = false;
function submitTellafriend(url, formobj) {
	var frmElements = $('#hm-savings-tellafriend input');
	$.each( frmElements, function(n, item) {
		if ($(item).attr('rdi:required') == 'true') {
			if($(item).val() == '') {
				$('#'+item.name + '-err').show();
				if ($('#'+item.name + '-errformat')) {
					$('#'+item.name + '-errformat').show();
				}
			} else {
				$('#'+item.name + '-err').hide();
			}
		}
	});
	if (validateTellafriend()) {
		if (!submitTellafriendBlock) {
			submitTellafriendBlock = true;
			$.ajax({
				//dataType: 'xml',
				type: "POST",
				url: url,
				data: formobj.serialize(),
				success: function(response) {
				//alert(response);
					closeTellFriend();
					//$('#savings-calculator-content').append(response);
					//$('#savings-tella-friend').append('<div class="clearfix">' + response + "</div>");
					$('#response-tellfriend').html(response );
					//$('#savings-tella-friend').html(response);
					//clonedTell.html().append(response);
					
				    submitTellafriendBlock = false;
				}
//				,error:function(XMLHttpRequest, textStatus, errorThrown)
//				{
//					alert(XMLHttpRequest.responseText);
//				}
			});
		}
	}
}

function validateTellafriend() {
	var isValid = true;
	var frmElements = $("#hm-savings-tellafriend input");
	
	//frmElements.each(frmElements,
	$.each(frmElements,
		function(n,item) {
			if ($(item).attr('rdi:required') == 'true' && ($(item).val() == '')) {
				$(item.name + '-err').show();
				isValid = false;
			}
		}
	);

	if (isValid) {
		//Validate emails
		var email = $("#email").val();
		if (!$.trim(email).match(/^[\w-_]+(\.[\w-_]+)*@([\w-_]+\.)+[a-zA-Z]{2,7}$/)) {
			isValid = false;
			$('#email-errformat').show();
		} else {
			$('#email-errformat').hide();
		}
		
		var femailv = $("#femail").val();
		var arrFemail = femailv.split(',');
		$.each( arrFemail,
			function(n, item) {
				if (!$.trim(item).match(/^[\w-_]+(\.[\w-_]+)*@([\w-_]+\.)+[a-zA-Z]{2,7}$/)) {
					isValid = false;
					$('#femail-errformat').show();
				} else {
					$('#femail-errformat').hide();
				}
			}
		);
	}

	return isValid;
}

function showPostalCode(chkbox) {
	if(chkbox.checked == true) {
		$('#tell_friend_zip').show();
		$('#zipcode').show();
		$('#zipcode').attr("rdi:required", "true");
	} else {
		$('#tell_friend_zip').hide();
		$('#zipcode').hide();
		$('#zipcode').attr("rdi:required", "false");
		$('#zipcode-err').hide();
	}
}

/*
jQuery.fn.customInput = function(){
	$(this).each(function(i){	
		if($(this).is('[type=checkbox],[type=radio]')){
			var input = $(this);
			
			// get the associated label using the input's id
			var label = $('label[for='+input.attr('id')+']');
			
			//get type, for classname suffix 
			var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
			
			// wrap the input + label in a div 
			$('
').insertBefore(input).append(input, label);
			
			// find all inputs in this set using the shared name attribute
			var allInputs = $('input[name='+input.attr('name')+']');
			
			// necessary for browsers that don't support the :hover pseudo class on labels
			label.hover(
				function(){ 
					$(this).addClass('hover'); 
					if(inputType == 'checkbox' && input.is(':checked')){ 
						$(this).addClass('checkedHover'); 
					} 
				},
				function(){ $(this).removeClass('hover checkedHover'); }
			);
			
			//bind custom event, trigger it, bind click,focus,blur events					
			input.bind('updateState', function(){	
				if (input.is(':checked')) {
					if (input.is(':radio')) {				
						allInputs.each(function(){
							$('label[for='+$(this).attr('id')+']').removeClass('checked');
						});		
					};
					label.addClass('checked');
				}
				else { label.removeClass('checked checkedHover checkedFocus'); }
										
			})
			.trigger('updateState')
			.click(function(){ 
				$(this).trigger('updateState'); 
			})
			.focus(function(){ 
				label.addClass('focus'); 
				if(inputType == 'checkbox' && input.is(':checked')){ 
					$(this).addClass('checkedFocus'); 
				} 
			})
			.blur(function(){ label.removeClass('focus checkedFocus'); });
		}
	});
};
*/

