var checkTimeout = null;
var timedOutString = "$('#popup #box_content').html('<h3>Request Timed Out</h3><p>Please <a href=\"javascript:location.reload(true)\">Reload this page</a>  to make sure you are logged in and your internet is connected.</p>');centerPopup();";

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

//Setup popup
// 0 means disabled; 1 means enabled
var popupStatus = 0;

function preloadPopup(){
	$('#popup #box_content').html('<div class="loading"><h3>Loading</h3></div>');
	centerPopup();
	loadPopup();
}

//loading popup with jQuery magic!
function loadPopup(){
	//loads popup only if it is disabled
	if(popupStatus==0){
		//$("#backgroundPopup").css({
		//"opacity": "0.7"
		//});
		$("#backgroundPopup").show();
/* 		$("#popup").fadeIn("normal",function(){$("#popupClose").fadeIn('normal');}); */
		$("#popup").show();
		$("#popupClose").show();
		popupStatus = 1;
		
	}
}

/* //disabling popup with jQuery magic! */
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
/* 		$("#backgroundPopup").fadeOut("slow"); */
		$("#backgroundPopup").hide();
/* 		$("#popup").fadeOut("slow"); */
		$("#popup").hide();
		popupStatus = 0;
/* 		$("#popupClose").fadeOut('normal'); */
		$("#popupClose").hide();
		$("#box_content").html('');
	}
}

/* //centering popup */
function centerPopup(){
/* 	//request data for centering */
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popup").height();
	var popupWidth = $("#popup").width();
/* //	alert('height:'+popupHeight+' width: '+popupWidth); */
/* 	//centering */
	var top = windowHeight/3-popupHeight/2;
	if(top < 0){
		top = 0;
	}
	$("#popup").css({
		"position": "fixed",
		"top":  top,
		"left": windowWidth/2-popupWidth/2
	});
	$("#popup").draggable();
	//only need force for IE6
	/*
	$("#backgroundPopup").css({
		"height": windowHeight
	});
*/
}

$(document).ready(function(){
	//LOADING POPUP
	//Click the button event!
	$("#button").click(function(){
		
		//centering with css
		centerPopup();
		
		//load popup
		loadPopup();
	});
	
	//CLOSING POPUP
	//Click the x event!
	$("#popupClose").click(function(){
		disablePopup();
	});
	
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
	
//Page load Requisites
	//Fade Flash away
	//setTimeout("$('.flash_container').fadeOut('slow');",3200);
	$('head').append('<style type="text/css">#find_a_bug{background:transparent url(/img/feedback_r.png) no-repeat scroll left 0px;}#find_a_bug:hover{background-position:left top;}</style>');

	$('body').prepend('<a id="find_a_bug" onClick="report_a_bug();" style="position:fixed;top:50px;right:0px;z-index:10;display:block;width:32px;height:140px;"></a>');	

});

function whatsthis(slug){
	checkTimeout = setTimeout(timedOutString, 10000);
	preloadPopup();
	params = 'ajax[do]=single';
	$.post(
		'/tips/single/'+slug,
		params,
		function(data){
			$('#popup #box_content').html(data);
			centerPopup();
			clearTimeout(checkTimeout);
		
		});
}

//Google Chart Simple encode snippet
var simpleEncoding = 
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function simpleEncode(valueArray,maxValue) {

var chartData = ['s:'];
  for (var i = 0; i < valueArray.length; i++) {
    var currentValue = valueArray[i];
    if (!isNaN(currentValue) && currentValue >= 0) {
    chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * 
      currentValue / maxValue)));
    }
      else {
      chartData.push('_');
      }
  }
return chartData.join('');
}
// End Google chart Simple encode



function report_a_bug(){
	preloadPopup();
	var params = 'ajax[do]=report_a_bug';
	$.post(
		'/ajax/report_a_bug',
		params,
		function(data){
			$('#box_content').html(data);
			centerPopup();
			$('#send_report').bind('click',function(){
				if($('#BugExplanation').val() > ''){
					

					var params2 = 'ajax[do]=report_a_bug&data[Bug][severity]='+$('#BugSeverity').val()+'&data[Bug][explanation]='+$('#BugExplanation').val();
					preloadPopup();
					$.post(
						'/ajax/report_a_bug',
						params2,
						function(data){
							if(data == 'sent'){
								
								$('#box_content').html('<h2>Thank You!</h2><p class="small_popup">Your report has been sent. Your feedback and reports will help us make Skimmit the way you like it.</p>');
							} else {
								$('#box_content').html(data);
								
							}
							centerPopup();
						}
					);
				} else {
					alert('Please type a helpful explanation before submitting this report. Thank you!');
					$('#BugExplanation').focus();
				}
			});
		}
	);
}

function signup(step){
	var style = 'height:345px; width:373px; background: url(/img/loading000.gif) no-repeat center center;'
	switch(step){
	
		case 2:
			$('#signup_box').html('');
			$('#signup_box').attr('style',style);

			$.post(
				'/ajax/signup_home/2',
				null,
				function(data){
					$('#signup_box').removeAttr('style');
					$('#signup_box').html(data);
				}
			);
		break;
		
		case 3:
		
			if($('#ConsumerPassCode').val() != undefined && $('#ConsumerPassCode').val() != ''){
				var params = 'data[Consumer][pass_code]='+$('#ConsumerPassCode').val();
				$('#signup_box').html('');
				$('#signup_box').attr('style',style);
				$.post(
					'/ajax/signup_home/3',
					params,
					function(data){
						$('#signup_box').removeAttr('style');
						$('#signup_box').html(data);
					}
				);
	
			} else {
				var params = null;
			}
		break;
		
		case 4:
			$.post(
				'/ajax/signup_home/4',
				null,
				function(data){
					$('#signup_box').removeAttr('style');
					$('#signup_box').html(data);
				}
			);
		
		break;
		
		
		case "new":
			$('#signup_box').html('');
			$('#signup_box').attr('style',style);
			$.post(
				'/ajax/signup_home/1',
				null,
				function(data){
					$('#signup_box').removeAttr('style');
					$('#signup_box').html(data);
				}
			);
		break;
		
		
		default:
			if($("input[name='data[Consumer][gender]']:checked").val() != undefined){
				gender = '&data[Consumer][gender]='+$("input[name='data[Consumer][gender]']:checked").val();
			} else {
				gender = '';
			}
			params = 
				'data[Consumer][first_name]='+$('#ConsumerFirstName').val()+
				'&data[Consumer][last_name]='+$('#ConsumerLastName').val()+
				gender+
				'&data[User][email]='+$('#UserEmail').val()+
				'&data[User][password]='+$('#UserPassword').val()+
				'&data[User][password_confirm]='+$('#UserPasswordConfirm').val()+
				'&data[Consumer][human_check]='+$('#ConsumerHumanCheck').val()+
				'&data[Consumer][birthday][month]='+$('#ConsumerBirthdayMonth').val()+
				'&data[Consumer][birthday][day]='+$('#ConsumerBirthdayDay').val()+
				'&data[Consumer][birthday][year]='+$('#ConsumerBirthdayYear').val()+
				'&data[Consumer][region_id]='+$('#ConsumerRegionId').val();

			$('#signup_box').html('');
			$('#signup_box').attr('style',style);

			$.post(
				'/ajax/signup_home/1',
				params,
				function(data){
					$('#signup_box').removeAttr('style');
					$('#signup_box').html(data);
				}
			);
		break;	
	
	}
	
}

function ajaxLogin(){
	var email = $('#UserEmail').val();
	var pass = $('#UserPassword').val();
	if(email != undefined && pass != undefined)
		params = 'data[User][email]='+email+'&data[User][password]='+pass;
	else
		params = null;
		
	$.ajax({
		url: '/ajax/ajax_login',
		data: params,
		type: "post",
		success: function(data){
			if(data == 1){
				window.location.reload();
			}
			else {
				$('#box_content').html(data);
			}
		}	
	});
}

function goSignup(){
	$('#box_content').html('<div style="width:373px;"><div id="signup_box"></div><div class="clear"></div></div>');
	if(signup("new")){
		centerPopup();
	}
	else{
		centerPopup();
	}
	loadPopup();
}
function loginPopup(){
	preloadPopup();
	$('#box_content').load('/ajax/ajax_login',function(){centerPopup();});
	
}
function fanIt(mId){
	$('.fan_'+mId).addClass('fan_load').removeClass('fan_del fan_add');
	var params = '';
	
	var ret = $.ajax({
		url: "/ajax/add_fan/"+mId,
		async: false,
		success: function(data){
			if(data == 1){
				$('.fan_'+mId).attr('href','javascript:unfanIt('+mId+')').attr('title','Remove me from Fans').addClass('fan_del').removeClass('fan_add fan_load');
			}
			else {
				preloadPopup();
				$('#box_content').html(data);
				centerPopup();
			}
		
		}
	
	}).responseText;
}

function unfanIt(mId){
	$('.fan_'+mId).addClass('fan_load').removeClass('fan_del fan_add');
	var ret = $.ajax({
		url: "/ajax/del_fan/"+mId,
		async: false,
		success: function(data){
			if(data == 1){
				$('.fan_'+mId).attr('href','javascript:fanIt('+mId+')').attr('title','Become a Fan').addClass('fan_add').removeClass('fan_del fan_load');
			}
			else {
				preloadPopup();
				$('#box_content').html(data);
				centerPopup();
			}
		
		}
	}).responseText;

}

var demo_next = 1;
function run_demo(next_step){

	demo_next = demo_next+1;
	switch(next_step){		
		
		case 1:
			$('#bubble_body').html('You start by texting "skimmit keyword" to 368266(DOTCOM) where "keyword" is what you are searching for.');
			$('#bubble').fadeIn(1000);
			$('#droid_x_screen').css('background-image','url(/img/phone_demo_sms_screen.png)');	
			$('#bubble').animate({bottom:"125px"},1000);	
			$('#demo_messages').animate({top:"245px"},1000);
		break;
		
		case 2:
			$('#bubble_body').html('The response you get is a max of 3 texts with a numbered list of Skimms to choose from. If we wanted the Skimm numbered (3) for Twizlberry, we reply just that number.');
			$('#bubble').animate({bottom:"165px"},500);
			$('#demo_messages').animate({top:"18px"},1200);

		break;
		
		case 3:
			$('#bubble_body').html('Text "3". That\'s Easy right?');
			$('#bubble').animate({bottom:"125px"},1000);
			$('#demo_messages').animate({top:"-10px"},500);
		break;
		
		case 4:
			$('#bubble_body').html('Take this message to Twizlberry and get your 10% off!');
			$('#bubble').animate({bottom:"125px"},1000);
			$('#demo_messages').animate({top:"-120px"},1200);			
		break;
		
		default: 
			demo_reset();
		break;
	}

}
function demo_reset(phone_id){
	$('#'+phone_id+' #bubble').fadeOut('normal');
	demo_next=1;
	$('#'+phone_id+' #droid_x_screen').css('background-image','none');
	$('#'+phone_id+' .demo_messages').css('top','300px');	
}

var demo_signup_step=1;
function demo_signup(next_step,phone_id){
	
	demo_signup_step = demo_signup_step+1;
	switch(next_step){		
		
		case 1:
			$('#'+phone_id+' #bubble_body').html('Start by texting "skimmit" to 368266(DOTCOM).');
			$('#'+phone_id+' #bubble').fadeIn(1000);
			$('#'+phone_id+' #droid_x_screen').css('background-image','url(/img/phone_demo_sms_screen.png)');	
			$('#'+phone_id+' #bubble').animate({bottom:"140px"},500);	
			$('#'+phone_id+' .demo_messages').animate({top:"245px"},1000);
		break;
		
		case 2:
			$('#'+phone_id+' #bubble_body').html('This is just asking you to confirm registration, allowing us to send you discounts. Replying S to any text message we send will manually unregister your phone. Click <a href="javascript:whatsthis(\'getting-texts\')">Here</a> for more text related info.');
			$('#'+phone_id+' #bubble').animate({bottom:"140px"},500);
			$('#'+phone_id+' .demo_messages').animate({top:"158px"},1200);

		break;
		
		case 3:
			$('#'+phone_id+' #bubble_body').html('Text "yes". Woah that was tough.');
			$('#'+phone_id+' #bubble').animate({bottom:"140px"},500);
			$('#'+phone_id+' .demo_messages').animate({top:"130px"},500);
		break;
		
		case 4:
			$('#'+phone_id+' #bubble_body').html('We use your zipcode to make sure the deals are near by to you.');
			$('#'+phone_id+' #bubble').animate({bottom:"140px"},500);
			$('#'+phone_id+' .demo_messages').animate({top:"52px"},1200);			
		break;
		
		case 5:
			$('#'+phone_id+' #bubble_body').html('Just reply your zip code');
			$('#'+phone_id+' #bubble').animate({bottom:"140px"},500);
			$('#'+phone_id+' .demo_messages').animate({top:"25px"},1200);			
		break;
		
		case 6:
			$('#'+phone_id+' #bubble_body').html('If we are offering a promo, you will get an coupon on signup. Otherwise just a warm welcome.');
			$('#'+phone_id+' #bubble').animate({bottom:"140px"},500);
			$('#'+phone_id+' .demo_messages').animate({top:"-65px"},1200);			
		break;
		
		default: 
			demo_reset(phone_id);
			demo_signup_step = 1;
		break;
	}

}


function quicksearch(){
	window.location='/coupons/search/'+$('#quicksearch_field').val();
	return false;
	
}

