var MOBILE_WIDTH = 205;
var MOBILE_HEIGHT = 126;

var columns;
var orderedId;

var currentOption;
var currentClass;  

var logoPosition;
var productPosition; 

var legalOverTimeOut;

var currentPhone;
var currentPage;
var totalPhones;


$(document).ready(function(){
	init();		
	activate();
	animateIn();
});

function init(){      
	currentClass = '.all';	
	orderedId = new Array();  	                       

	onResize();
	
	var windowHeight = $(window).height();
	var windowRows = Math.ceil(windowHeight/MOBILE_HEIGHT);
	$('.phone').hide();

	currentPhone = 0;
	showPhonesPage();

	preloadImages("img/phone-big.jpg", "img/phone-big-screen.jpg", "img/logo-big.png", "img/evo-big.jpg");
	
	Cufon.replace('h3', {fontFamily:'BertholdStandardBQBold'});
	sendStat('/loadstart');
	sendStat('/firsts');
}

function showPhonesPage(){
	var totalLinesToShow = Math.floor($(window).height()/MOBILE_HEIGHT) + 1;
	totalPhones = currentPhone + totalLinesToShow * columns - 5;
	if(currentPhone!=0) totalPhones -=1;
	$('.phone').each(function(index) {
		if(index>=currentPhone && currentPhone<totalPhones){
			$(this).show();
			var id = $(this).attr('id');
			orderedId[index] = id;
			loadAnimation(this);
			currentPhone++;
		}
	});	
	
	showExtraPhones();
}

function showAllPages(){
	while(currentPhone<$('.phone').length){
		showPhonesPage();
	}
}

function showExtraPhones(){
	if(currentPhone==$('.phone').length){
		if (!$.browser.msie){
			$('.extra').remove(); 
			addExtraPhones();
		}
	}
	activatePhones();
}

function loadAnimation(phone){
	var animation = $('.thumb .animation', phone);
	var animationUrl = animation.attr('id');	
	if(animationUrl!=undefined){
		animation.hide();
		var image = new Image();
		$(image).attr('src', 'http://a124.g.akamai.net/7/124/51009/v001/nowisgood.download.akamai.com/51009/firsts/animation/' + animationUrl);
		//$(image).attr('src', 'http://localhost:8888/firsts/animation/' + animationUrl);
		animation.append(image);
		$(image).load(function() {
			if(!zoomOut && !$.browser.msie){
				setTimeout(function() { animation.fadeIn(200 + Math.random() * 50); }, Math.random() * 2000);
			}else{
				animation.show();
			}
		});
	}
}

function activate(){	
		
	$(window).bind('resize', function() {
	   onResize();
	});
	
	$(".thumb").hover(function() {
		if (!$.browser.msie) $(this).children(".info").fadeIn(150);
		else $(this).children(".info").fadeIn(0);
	} , function() {
		if (!$.browser.msie) $(this).children(".info").fadeOut(150);
		else $(this).children(".info").fadeOut(0);
	});
	
	$('#all').click(function(){filter('all', $(this));});
	$('#claimed').click(function(){filter('claimed', $(this));});
	$('#unclaimed').click(function(){filter('unclaimed', $(this));});

	currentOption = $('#all');
	currentOption.addClass("selected");	
	
	
	$('#product').click(function(){
		sendStat('/firsts/evo4g');
		location.href = 'http://now.sprint.com/firsts/evo4g/';
	});
	
	$('#shareButton').hover(
	  function () {
		$('#sharePanel input').val(window.location);
		$('#sharePanel #email').attr('href', $('#sharePanel #email').attr('href').replace(/URL/ig, escape(window.location)));	
		$('#sharePanel #twitter').attr('href', $('#sharePanel #twitter').attr('href').replace(/URL/ig, escape(window.location)));	
		setTimeout(function() { 
			$('#sharePanel input').focus();	
			$('#sharePanel input').select();
		}, 1);	
		$(this).append($('#sharePanel'));
	    $('#sharePanel').fadeIn('fast');
	  }, 
	  function () {
	    $('#sharePanel').fadeOut();
	  }
	);
	
	$('#legal').hover(
	  function () {
		clearTimeout(legalOverTimeOut);
		$(this).stop();
		var inc = $("#legalContainer").height() + 60;
		$(this).animate({height: inc + 'px'}, 500);		
		$('#arrow').css('background-position', '-190px 0px');
	  }, 
	  function () {
		$(this).stop();
		var legal = $(this);
		legalOverTimeOut = setTimeout(function() { 
			legal.animate({height: '28px'}, 500); 
			$('#arrow').css('background-position', '-180px 0px');
		}, 400);			
	  }
	);
	
	$(window).scroll(checkScroll);
}

function checkScroll(){
	var scroll = $(window).scrollTop();
	var totalScroll = $("#container").height() - $(window).height() + 140;
	if(scroll/totalScroll>=1){
		showPhonesPage();
	}
}

function animateIn(){
	$('#loading').hide();
	$('#content').show();
	
	/*
	if(!zoomOut){
		show();
	}else{
		$(".phone .thumb").each(function(index) {
			var thumb = $(this);
			thumb.show();
		});
	}
	*/
	
}

function show(){
	if (!$.browser.msie){
		$(".phone .thumb").each(function(index) {
			var thumb = $(this);
			thumb.css('opacity', 0);
			setTimeout(function() { thumb.fadeTo(200, 1); }, 400 + 3000 * Math.random());	
		});	
	}
}

function onResize(){

	if (!$.browser.msie){
		$(currentClass).each(function(index) {
			$(this).insertAfter($(currentClass + ":nth-child("+index+")"));
		});
	}	
	
	columns = Math.floor($("#container").width()/ MOBILE_WIDTH);     	
	
	var windowHeight = $(window).height();                                          
  	windowHeight -= 114;
	var windowTotalRows = Math.round(windowHeight/MOBILE_HEIGHT);    
	var productRow = (windowTotalRows-3); 
	if(productRow<=0){             
		productPosition = columns-1;
		logoPosition = columns-1;
	}else{
	 	productPosition = (productRow * columns) + (columns-1) - 1; 
	  	logoPosition = columns;
	}                
	
	if(columns==2){
		productPosition = 4;
		logoPosition = 2;
	} else if(columns==3){      
		productPosition = productPosition -1;
	}
	                   
	$("#logo").insertAfter($(currentClass+":nth-child("+logoPosition+")"));
	$("#product").insertAfter($(currentClass+":nth-child("+productPosition+")"));
	$("#content").css('width', (columns * MOBILE_WIDTH) + 'px');
	
	
	showExtraPhones();	

}     


function activatePhones(){
	$('.phone').each(function(index) {
		var id = $(this).attr('id');	    
		if(id.substr(0,6)=="create"){
			id= "create-your-own-0";             
		}
		var href = "zoom.php?c=" + columns+ "&p=" + productPosition + "#/"+ id;
		$(this).unbind('click');
		$(this).click(function() {
			$('#loading').show();
			$('#container').hide();
  			window.location = href;			
		});
	});
}

function filter(value, button){
	if(currentPhone!=$('.phone').length){
		showAllPages();
	}
	currentOption.removeClass("selected");  
	$('.extra').remove();  
	currentOption = button;
	currentOption.addClass("selected");
	
	$("#product").insertAfter($(".phone").last());	
	$("#logo").insertAfter($(".phone").last());
	$('.phone').show();
	switch(value){
		case 'claimed':
			$(".unclaimed").insertAfter($(".phone").last());
			$('.unclaimed').hide();
			currentClass = '.claimed';
			sendStat('/firsts/filter/claimed');
			break;	
		case 'unclaimed':
			$(".claimed").insertAfter($(".phone").last());
			$('.claimed').hide();		
			currentClass = ".unclaimed";
			sendStat('/firsts/filter/unclaimed');
			break;	
		default: 
			for(var i=0; i<orderedId.length; i++){
				var phone = $('#' + orderedId[i])
				phone.insertAfter($(".all").last());
			}
			currentClass = ".all";
			sendStat('/firsts/filter/all');
	}	
		
	$('.create').insertAfter($(currentClass).last());
	$("#logo").insertAfter($(currentClass+":nth-child("+logoPosition+")"));
	$("#product").insertAfter($(currentClass+":nth-child("+productPosition+")"));
	
	if (!$.browser.msie) addExtraPhones();
	activatePhones();
	show();   
}

function addExtraPhones() {    
	var total = $(currentClass).length;   
	var dif = columns - (total+1); 
	var startHeight = $('#content').height();
	var extraId = 1;
	
	do{
		var newPhone = $('.create').clone();
		newPhone.addClass("extra");
		newPhone.removeClass("create");
		newPhone.attr("id", "create-your-own-" + extraId);
		if(dif>0){
			newPhone.insertAfter($(currentClass).last());			
			dif--;
		}else{
		 	newPhone.appendTo('#phoneContainer'); 
		}
		$("#create-your-own-" + extraId + ".thumb").css('opacity', 1);
		extraId++;     
		if(dif>0) startHeight = $('#content').height(); 

	}while(startHeight == $('#content').height() || dif>0);
	$('.extra').last().remove();
}

function preloadImages(){
	var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
    }
}





