//20091104
var minimized = false;
var scroll_position = 0;
var bottom_cards = $('#card-holder .small_card').length;
var bottom_card_pos=1;
var question_data;
var focus_submitted = false;
var total_questions;
var current_question;
var browse_time = 0;
var browse_timer;
var current_offer = '';
var click_count = 0;
var bonus_available;
var question_page = 1;
var current_card_id;
var show_instructions = false;
var current_card_bg;
var responses;

$(document).ready(function(){
	jQuery.fx.off = true; // Globally disables all animations.
	
	bonus_available = $('.bonus-card-mask span.card').length;
  	// Validate stuff 
	if ($('body').hasClass('activation-landing')){
		$('form').validate();	
		$('#recipient_gender_id option').eq(0).html('select...');
	}

	$('.activation-form input').focus(function(){
	  if (focus_submitted == false)
	    $.post('/activation/onform');
	  focus_submitted = true;
	});
	
	if($('#amt_cards')[0])
		var amt_cards = document.getElementById('amt_cards').value;
	else
		var amt_cards = 0;
		
	var only_card = 0;


	// ADJUST THE HEIGHT OF THE TOP FRAME
	var height = $(window).height() - 116;
	if (amt_cards > 1) {
		$(window).load(function () {
			$('.frames .container-scroll').css({ "height": height + "px" });
		});
  
		$(window).resize(function() {
			height = $(window).height() - 116;
			$('.frames .container-scroll').css({ "height": height + "px" });
		});
	}

	// single card layout
	if (amt_cards == 1 && document.getElementById('only_card') != null) {
		only_card = document.getElementById('only_card').value;
		current_card_id = only_card;

		//$('.card-drop-top').attr('style', 'height:20px;');

		$.getJSON('/activate/question', {card:current_card_id}, function(data, status) {

			question_data = data;
			total_questions = data.count;
			current_question = 1;

			/*
			$('.card-questions').html('');
			$('.card-questions').attr('style', '');
			*/
			$('.text b').html(data.count);
			//showFirstQuestion();
			showFirstQuestion1(data);
		});
	}


	// START DRAGGABLE
	$('span.card').draggable({revert: true});
	$(".card-drop-target").droppable({
	  activeClass: 'droppable-active',
	  drop: function(event, ui) { 
		

		if($('.current-card').attr('id') != 'undefined'){
			var id = $('.current-card').attr('id');
			$('.current-card').remove();
			$('#' + id).attr('style', 'display:block');
		}
			
		//hide the card target and show the card
		$('.card-drop-target').hide();
		$('.card-questions').show();
		$('.ui-draggable-dragging').clone().insertBefore('.card-drop-target').addClass('current-card');
		$('.current-card').removeClass('ui-draggable-dragging');
		$('.current-card').css({'top': '', 'left': ''});
		$('.card-reset').show();
		$('.sidebar .step').show();
		$('.sidebar').addClass('hascard');
		$('.ui-draggable-dragging').attr('style', 'display:none');	
		$('.container-scroll').scrollTo(135, 800, {queue:false} );
		current_card_id = $('.current-card').attr('id');
	    current_card_bg = $('.current-card').css('background-image').slice(4, -1);

		$.getJSON('/activate/question', {card:current_card_id}, function(data, status) {
			question_data = data;
			total_questions = data.count;
			current_question = 1;

			$('.card-questions').html('');
			$('.card-questions').attr('style', '');
			$('.text b').html(data.count);
			showFirstQuestion();
		});
	  }
	});
	$('#card-holder-frame').scrollTo( 0,0, {queue:false} );	
	
	
	//bind bonus card scrollers
	$('.sidebar.bonus-card a.left').live('click', bonus_scroll_left);
	$('.sidebar.bonus-card a.right').live('click', bonus_scroll_right);

	// Disable "Continue" button on default...
	$('#cssbutton.inactive').attr('disabled', 'disabled');
});

function showQuestion(data, count){

	var html = '';
	var new_question = $('#card-question-template').clone();
	new_question.attr('id', 'current-question');
	$('span.step').text(current_question + ' of ' + total_questions);
	//fill out data
	new_question.find('#question').text(question_data.questions[current_question-1].question);
	for(i=0; i < question_data.questions[current_question-1].answers.length; i++) {
	  var qAnswer = question_data.questions[current_question-1].answers[i];
	  qAnswer = qAnswer.split('//');
	  
		html +=	'<p><input class="checkbox" value="'+i+'" type="radio" onclick="next_question('+qAnswer[0]+')" id="question'+ (i+1) +'"><label for="question'+ (i+1) +'">' +qAnswer[1]+'</label><br></p>';
	}
	new_question.find('#answers').html(html);
	
	current_question++;
	new_question.appendTo('.card-questions');
	$('#current-question').css({'display':'none'});
	var center_height = $('#current-question').height() + 65;
	//expand the sidebar
	$('.card-center').css({height: center_height  + 'px'});
	$('.card-static-buttons').show();
	$('#current-question').show();	
}

function showFirstQuestion1(question_data){
	var html = '';

	$('#step').text(current_question + ' of ' + total_questions);
	//fill out data
	$('#question').text(question_data.questions[current_question-1].question);

	for(i=0; i < question_data.questions[current_question-1].answers.length; i++) {
	   var qAnswer = question_data.questions[current_question-1].answers[i];
  		qAnswer = qAnswer.split('//');
		html +=	'<div id="answer"><input id="question'+(i+1)+'" type="radio" name="" value="'+i+'" onclick="next_question('+qAnswer[0]+')" /><span class="spananswer">' + qAnswer[1] + "</span></div>\r\n";
	}
	$('#answers').html(html);
	current_question++;

	// 100129/HPJ - Handle inactive CSS buttons
	$('#cssbutton').addClass('inactive');
}

function showFirstQuestion(data, count){
	// 100106/HPJ - Adjust height earlier to address sporadic JS display issue.
	$('.card-center').css({height:'auto'});
	
	var html = '';
	responses = new Array();

	var new_question = $('#card-question-template').clone();

	new_question.attr('id', 'current-question');
	$('span.step').text(current_question + ' of ' + total_questions);

	//fill out data
	new_question.find('#question').text(question_data.questions[current_question-1].question);

	for(i=0; i < question_data.questions[current_question-1].answers.length; i++) {
	   var qAnswer = question_data.questions[current_question-1].answers[i];
  	   qAnswer = qAnswer.split('//');
	
		html +=	'<p><input class="checkbox" value="'+i+'" type="radio" onclick="next_question('+qAnswer[0]+')" id="question'+ (i+1) +'"><label for="question'+ (i+1) +'">' +qAnswer[1]+'</label><br></p>';
	}
	new_question.find('#answers').html(html);
	
	current_question++;
	new_question.appendTo('.card-questions');
	$('#current-question').css({display: 'none'});

	var center_height = $('#current-question').height() + 65;
	//expand the sidebar
	$('.card-center').css({height: center_height  + 'px'});
	$('.card-static-buttons').show();

	$('#current-question').show();
}

// debugging function to do the equivilent of a PHP print_r in javascript
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


//called when all questions are answered
function showActivate(){

	$('span.step').html('');

	$('.card-questions').append('<div id="current-question" class="single-question"><span class="update-thanks"><br/>Thank you for<br/>answering our<br/>questions!<br/><br/></span></div>');
	$('.card-center').css({height: '120px'});
	$('#current-question').css({display: 'none'});

	var grab_current_id = current_card_id.slice(6);

	if (grab_current_id == '') {
		grab_current_id = current_card_id;
	}
	
	// if grab_current_id is still null, grab it from the hidden field
	if (grab_current_id == '') {
		grab_current_id = document.getElementById('only_card').value;
	}

	$('.card-static-buttons').find('img').bind('click', function(){ fly( grab_current_id ) });
	
	$('.card-static-buttons').find('img').attr('src', document.getElementById('button_activate_card').value);
	$('#current-question').show();

	// 100129/HPJ - Handle inactive CSS buttons
	$('#cssbutton').removeClass('inactive').attr('href','/activate/share');

}

function next_question(response){
	$('#question').empty();
	$('#answers').empty();

        $.getJSON('/activate/answer', {question:response}, function(results_answer){

    	if(current_question > total_questions){
			$('div#current-question').html('<span class="update-thanks"><br/>Thank you for<br/>answering our<br/>questions!<br/><br/></span>');
			$('#cssbutton').removeClass('inactive');
			$('#cssbutton').removeAttr('disabled');
    	} else {
			var only_card = $('#only_card').val();
			current_card_id = only_card;
			$.getJSON('/activate/question', {card:current_card_id}, function(data, status) {
				showFirstQuestion1(data);
			});
    	}
  });
}

function submit(id){

	$('.card-questions').hide();

	//show the bar if it's hidden
	if(minimized){
		minimize();
	}
	
	//add card to tray
	$('#left-content-no-cards').attr('style', 'display:none');
	$('#left-content-cards').attr('style', 'display:block');
	$('.card-questions').hide();
	
	$('#card-holder').append('<span class="small_card" id="'+id+'2"></span>');
	$('.current-card').hide();
	$('.current-card').remove();
	bottom_cards++;
	
	$('#card-count').html('| '+bottom_cards+' card activated');
	if(bottom_cards > 3) {
		scroll_right();
	} else {
		scroll_left();
	}
		
	//make continue button active
	$('a.button').addClass('active');
	
	reset();
	
	return false;
}

function reset(remove){	
	question_data = null;
	question_page = 1;
	$('.sidebar').removeClass('hascard');
	$('.current-card').remove();
	$('.card-reset').hide();
	$('.cards').append($('.current-card'));
	
	if(remove) {
		$('#' + current_card_id).css({'display': 'block'});
	}
	
	current_card_id = null;
	
	$('.card-drop-target').fadeIn();
	$('.card-center').css({ height: '33px'});
	$('b.update-message').text('these');
	$('.card-question-2').html('<strong></strong><form method="post" action="" class="jNice question"><fieldset></fieldset></form>');
	$('.card-question-1').html('<strong></strong><form method="post" action="" class="jNice question"><fieldset></fieldset></form>');
	$('.card-question-1').attr('style', 'left:0');
	$('.card-questions').attr('style', 'left:0');
	$('.card-question-2').attr('style', 'left:240px');	
	$('.card-static-buttons').hide();
	//$('.card-static-buttons').slideUp();
	$('.card-static-buttons').find('img').unbind('click');
	$('.card-static-buttons').find('img').attr('src', $('#button_activate_card_grey').val());
}

function fly(offer){

	// $('.card-static-buttons').slideUp();
	// $('.card-static-buttons').find('img').bind('click', function(){ return false });
	// $('.card-static-buttons').find('img').attr('src', '/images/button_activate_card_grey.gif');

  	//$.post('/activate/set', {offer:offer})


  	$.getJSON('/activate/set', {offer:offer}, function(return_vals) { /* alert('return_vals is: ' + return_vals); */ });

	var id = current_card_id,
	    bg = current_card_bg;
	if(bg == undefined)
		bg = '';
	
	//IE puts quotes around this, remove them
	bg = bg.replace(/["]/g,'');
	
	//show the bar if it's hidden
	if(minimized)
		  minimize();

	// if(responses)
	// 		$.post('/activate/response', {'response': responses.join(','), 'offer': current_card_id.slice(6)});
//	$('#current-question').remove();
	
	//scroll cards so there's an empty space for the new one
	if(bottom_cards > 3){
		while((bottom_cards - bottom_card_pos) > 2 ){
			scroll_right();
		}
	}

	
	//add card to tray
	$('#left-content-no-cards').attr('style', 'display:none');
	$('#left-content-cards').attr('style', 'display:block');
	
	bottom_cards++;


	$('#card-holder').append('<span class="small_card" id="'+id+'_sm"><img src="'+bg+'" alt="offer preview" width="114"/></span>');


	if(bottom_cards == 1)
		$('#card-count').html('| '+bottom_cards+' card activated');
	else
		$('#card-count').html('| '+bottom_cards+' cards activated');
	
	//move back to drop
	var dropable = $('.current-card').offset();
	var target = $('#' + id + '_sm').offset();
	var final_place = $('#' + id + '_sm').position();
	start_x = dropable.left - target.left + 38;
	start_y = dropable.top - target.top + 27;

	$('#' + id + '_sm').attr('style', 'position: absolute; left: ' + start_x + 'px;top: ' + start_y + 'px');

	//remove the large card
	/*$('.current-card').fadeOut('slow', function(){
		$('.current-card').remove();
	});*/
	//animate the flying
	$('#' + id + '_sm').animate({ 
		left: final_place.left + 'px', top: final_place.top+'px'}, 1200, null, function(){
			
			bottom_cards = $('.card-widget span.small_card').length;

			$('#' + id + '_sm').attr('style','');
			if(bottom_cards > 3) {
				scroll_right();
			} else {
				scroll_left();
			}
						
		});
		
	//make continue button active
	$('a.button').addClass('active');
	$('span.step').text('');

	if($('body.share')[0]){
		//alert('share');
	} else {
		reset();
	}
	return false;	
}

function minimize(){
	if(!minimized){
		var bot_height = 15;
		minimized = true;
		$('.toggle').css({'background': 'url(http://static.dukky.com/images/icon_maximize.gif)'});
		$('#left-content-cards').animate({'margin' : '-10px 0 0 0'}, 1500);
	} else {
		var bot_height = 116;
		minimized = false;
		$('.toggle').css({'background': 'url(http://static.dukky.com/images/icon_minimize.gif)'});
		$('#left-content-cards').animate({'margin' : '0'}, 1500);
	}
	var top_height = $(window).height() - bot_height;
	$('.footer-frame').animate({ 
		height: bot_height + 'px'}, 1500);
	$('.container-scroll').animate({ 
		height: top_height + 'px'}, 1500);						
}

function next_page(){
	//get all the cards in card-holder to pass to next page
	var url="activation3.php?cards="; 
	$('#card-holder').children().each(function(count){
		var this_id =$(this).attr('id');
		url += this_id + ",";
	});
	url += '0';
	window.location.href = url;
}

function scroll_right(count){


	if(count) {
		bottom_card_pos += count;
		scroll_position +=  (count * 124);
	} else {
		scroll_position +=  124;
		bottom_card_pos++;
	}

	if (bottom_cards < 1) 
		bottom_cards = document.getElementById('count_cards').value;


	if(scroll_position > (124 * (bottom_cards-1)))
		scroll_position = (124 * (bottom_cards-1));

	$('#card-holder-frame').scrollTo( scroll_position,500, {queue:false} );

	if(bottom_card_pos > 1) {
		activate_left_buttons();
	}	
	
	if(bottom_card_pos > 3) {
		deactivate_right_buttons();
	}	
}

function scroll_left(count){
	if(count) {
		bottom_card_pos -= count;
		scroll_position -=  (count * 124);
	} else {
		scroll_position -=  124;
		bottom_card_pos--;
	}

	if (bottom_cards < 1) 
		bottom_cards = document.getElementById('count_cards').value;

	if(bottom_card_pos < 1)
		bottom_card_pos = 1;
		
	if(scroll_position < 0)
		scroll_position = 0;
	$('#card-holder-frame').scrollTo( scroll_position,500, {queue:false} );
	
	if(bottom_card_pos < 2) {
		deactivate_left_buttons();
		bottom_card_pos = 1;
	}
	
	if((bottom_cards - bottom_card_pos) > 3){
		activate_right_buttons();
	}
}

function activate_left_buttons(){
	$('.leftButtonSkip').attr('src', document.getElementById('skip_left_active').value);
	$('.leftButton').attr('src', document.getElementById('scroll_left_active').value);
}

function deactivate_left_buttons(){
	$('.leftButtonSkip').attr('src', document.getElementById('skip_left').value);
	$('.leftButton').attr('src', document.getElementById('scroll_left').value);
}

function activate_right_buttons(){
	$('.rightButtonSkip').attr('src', document.getElementById('skip_right_active').value);
	$('.rightButton').attr('src', document.getElementById('scroll_right_active').value);
}

function deactivate_right_buttons(){
	$('.rightButtonSkip').attr('src', document.getElementById('skip_right').value);
	$('.rightButton').attr('src', document.getElementById('scroll_right').value);
}

//For Share Page
var GB_ANIMATION = true;

function share_facebook(msg, domain, code){
    sharer2 = window.open('http://www.facebook.com/sharer.php?u=' + domain + '&t=' + encodeURIComponent(msg), 'sharer', 'toolbar=0,status=0,width=626,height=436');
    share_callback('1', code);
    return false;
}
var sharer2;

function share_twitter(msg, code){
    sharer2 = window.open('http://twitter.com/home?status=' + encodeURIComponent(msg) + code,'sharer2','toolbar=0,status=0,width=840,height=375');
    share_callback('2', code);
    return false;
}

function share_email(this_window, code){
	//setTimeout(function(){
		//$('#at16sub').bind('click', function(e){
			//if($(this).val() == 'Send'){
				//alert('Sent!');
				sharer2 = window.open();
				sharer2.close();
				share_callback('3', code);
			//}
		//});
	//}, 00);
}

function share_sms(code){
    sharer2 = window.open('/activate/sms','sharer2','toolbar=0,location=0,menubar=0,status=0,width=500,height=300');
	share_callback('4', code);	// 100112/HPJ - Make '4' media service for SMS; updated in dukky/social_media table.
	return false;
}

function share_callback(mediaService, code){
		/*
		if(!sharer2.closed){
			//alert('in share_callback sharer2.closed');
			setTimeout(function(){share_callback(mediaService, code)}, 1500); 
		}else{
		*/
		//alert('in share_callback "else"');

		//console.log(mediaService);
		//they closed the share window, assumed they shared it
		
		/*
	 	$.getJSON('/activate/callback', {mediaService:mediaService, code:code}, function(data) {
			//question_data = data;
            //total_questions = data.count;
            //current_question = 1;

            //$('.card-questions').html('');
            //$('.card-questions').attr('style', '');
            //$('.text b').html(data.count);
            //showFirstQuestion();
        });
		*/

        $.ajax({
        	url: '/activate/callback',
        	dataType: 'json',
        	data: {mediaService:mediaService, code:code},
        	async: false,
        	success: function(d){
        		// success code
        		// alert('callback called!');
        	}
        });

		//$.post('/activate/referred', {'service': mediaService});
		$.ajax({
			type:'POST',
        	url: '/activate/referred',
        	data: {service: mediaService},
        	async: false,
        	success: function(d){
        		// success code
        		// alert('referred called!');
        	}
        });
        
		shared();
	//}
}


function shared(){
	//bonus cards
	if($('.sidebar.bonus-card')[0]){
		if($('.sidebar .noshow')[0]){
			var card_id = $($('.sidebar .noshow')[0]).attr('id').split('offer_')[1];
			$($('.sidebar .noshow')[0]).removeClass('noshow');
			
			//alert(card_id);
			bonus_scroll_right();			
			share_fly(card_id);
		}
		
		
		
	} else {
	//sweepstakes
	
	}

	$('#gift_card_image').fadeOut(function(){
		$('#gift_card_image').attr('src', $('#winner').val());
		$('#gift_card_image').fadeIn();
	});

	return false;
}

var bonus_scroll_pos = 0;
var bonus_scroll_count = 2;
var card_width = -233;
function bonus_scroll_left(){
	jQuery.fx.off = false;
	var activated_count = $('.sidebar.bonus-card span.card:not(.noshow)').length;
	var pos = $('.sidebar.bonus-card .bonus-card-mask').css('left').split('px')[0] / 233;
	
	pos++;
	
	if(pos > 0)
		return false;
	
	$('.sidebar.bonus-card .bonus-card-mask').animate({'left': pos*233 }, 200);
	
	if( (activated_count + pos) > 1)
		$('a.right').addClass('active');	
	else
		$('a.right').removeClass('active');	
	
	if(pos > -1)
		$('a.left').removeClass('active');
		
	if(pos < 0)
		$('a.left').addClass('active');
}

function bonus_scroll_right(){
	jQuery.fx.off = false;
	var activated_count = $('.sidebar.bonus-card span.card:not(.noshow)').length;
	var pos = $('.sidebar.bonus-card .bonus-card-mask').css('left').split('px')[0] / 233;
	
	
	if(activated_count < 2 || (activated_count + pos) <= 1)
		return false;
		
	pos--;
	
	$('.sidebar.bonus-card .bonus-card-mask').animate({'left': pos*233 }, 200);

	if( (activated_count + pos) > 1)
		$('a.right').addClass('active');	
	else
		$('a.right').removeClass('active');	
	
	if(pos > -1)
		$('a.left').removeClass('active');
		
	if(pos < 0)
		$('a.left').addClass('active');
}

function share_instructions(){
	if(!show_instructions){
		var top = (($(document).height()/2)-225);
		$(document.body)
			  .append("<div id='GB_overlay'></div><div id='GB_clear' style='left: "+(($(document).width()/2)-400)+"px; top: "+top+"px'>To redeem all of your great savings and<br/>promotions, just select any of the cards<br/>below in your queue.</div>");
		show_instructions = true;
	}
	$("#GB_overlay").bind('click', function() {
		$("#GB_overlay").remove();
		$("#GB_clear").remove();
	});
}

function show_site(url, offer, offerId, imgUri){
	$.post('/activate/visit', {'offerId': offerId});
	current_offer = offerId


	$("#GB_clear").remove();
	$("#GB_overlay").remove();
	$('.right-content div').html('<img width="114" src="'+imgUri+'" alt="offer preview"/><div class="coupon_details"><strong>Coupon Details</strong><br/>'+offer+'</div>');
	$('.right-side > .right-content').addClass('cdetails');
	var qFrame = $('<iframe onload="inc(); " id="shopping-frame" src="' + url + '" width="100%" height="100%"></iframe>');
	$('.container-scroll').html(qFrame);	
	start_timer(offerId, qFrame);
}


var start_timer = function(offerId, qFrame){
	if (browse_time != 0){
		stop_timer(offerId);
		return;
	}	
	
	browse_timer = setInterval(function(){browse_time++}, 1000);
	$('#shopping-frame').live('load', function(){
		click_count++;
	//	console.log(click_count);
	});
}
var inc = function(){
	click_count++;
//	console.log(click_count + 'xxx');
}
var stop_timer = function(offerId){
	clearInterval(browse_timer);
	var stop_time = browse_time;
	var clicks = click_count;
	browse_time = 0;
	click_count = 0;

	$.post('/activate/leave', {'offerId': offerId, 'time': stop_time, 'clicks' : clicks});
}

$(window).live('unload', function(){
	if ($('iframe').is('iframe'))
		stop_timer(current_offer);
});


function share_fly(card_id){
	if(bonus_available > 0){
		bonus_available--;
		$('#bonus_available').text(bonus_available);
		current_card_id = card_id;
		$('#offer_' + card_id).addClass('current-card');
		current_card_bg = $('#offer_'+current_card_id).css('background-image').slice(4, -1);
		var new_card = '#' + current_card_id + '_sm';
		bonus_scroll_count--;
		old_offer_id = current_card_id;
		var link = $('#'+old_offer_id+ ' input.link').val();
		var details = $('#'+old_offer_id+ ' input.details').val();
		var offer_id = current_card_id.split('offer_')[1];
		fly(card_id);
		
		$('#'+old_offer_id+'_sm').bind('click', function(){
			show_site(link, details, offer_id,current_card_bg );
		});
	//	$('#'+current_card_id).remove();
	}
}

