BUY_NOW_LABEL = "Buy Now";
PROMO_LABEL = "FREE Phone + Airtime Package";
IMAGE_PATH = "";
CURRENCY_LABEL = "$";
NUM_RESULT_COLS = 3;
FEATURE_LIMIT = 4; // Max number to display for feature listings

var activePhones = new Array();
var phones = new Array();  
var features = new Array();
var windowDimensions = new Array();
hasFeature = false;


//var url = 'http://vsfdbea03:8800/admin/preview/phones/phone-json?callback=?';
var url = 'http://web.virginmobileusa.com/phones/phone-json?callback=?';
//var url = 'http://www.clicksnsuch.com/phones-json.json?callback=?';

$(document).ready(function(){
//alert(url);
	$.getJSON( url,

        	function(data){

			//alert('hello world');
        });
  });
  
  
  function startDragDrop() {
  	/*$("#phoneListing .phoneThumb").draggable({helper: 'clone'});
	$("#compareDropZone li").droppable({ 
    	accept: ".phoneThumb", 
    	drop: function(ev, ui) { 
        	ui.draggable.clone().fadeOut("fast", 
        		function() { 
            	$(this).fadeIn("fast") 
        	}).appendTo($(this).empty()); 
    	} 
	});*/
  }
  
  
  function buildFilters() {

//alert("building filters");
  	 $("#phonePriceFilter a").click(function() {
	  $("ul#phonePriceFilter li a").removeClass("active");
	  $(this).addClass("active");
	  sortByPrice(this.id);
      return false;
	});
	
	$('#phoneFeatureFilter li input:checkbox').click( function() {
			searchByFeature();
	});

  }
  
  function sortByPrice(type) {
  	$("#phoneFeatureFilter input").attr('checked', ''); 
	
	switch(type) {
		case "deals":
		var dealPhones = new Array();
		for (x=0; x<phones.length; x++) {
			if (phones[x].phone_deal) {
				dealPhones.push(phones[x]);
			}
			
			
		}
		$("#phoneListing").empty();
		activePhones = dealPhones;
		displayPage(dealPhones);
		startDragDrop();
		break;
		
		 
		
		
		
		case "free":
		var freePhones = new Array();
		for (x=0; x<phones.length; x++) {
			if (phones[x].phone_free) {
				freePhones.push(phones[x]);
			}


		}
		$("#phoneListing").empty();
		activePhones = freePhones;
		displayPage(freePhones);
		startDragDrop();
		break;

		default:
		$("#phoneListing").empty();
		activePhones = phones;
		displayPage(phones);
		startDragDrop();
		break;	 
	}
  }
  
  function sortNumber(a,b) {
	return a - b;
}
  
  function searchByFeature(){
  tmpPhoneFeatures = new Array();
 
 tmpPhones = new Array();
  


  promo = $("#free").hasClass("active");
  
  
  	$("#phoneFeatureFilter input:checkbox").each(function () {
		if($(this).attr('checked')) {
			var checkValue = $(this).val();	
//alert(checkValue);
			tmpPhoneFeatures.push(checkValue);
//alert(tmpPhoneFeatures);
		}
	});
	
	
	
	
	for (r = 0; r < phones.length; r++) {
		tmpFeatures = tmpPhoneFeatures;
		
		//alert(sortNumber);
		//tmpFeatures.sort(sortNumber);

		//alert(tmpFeatures);

		//tmpFeatures = tmpFeatures.join(",");
		
		
		
		//alert("tmpFeatures " + tmpFeatures.length); ///what's checked

		tmpPhone = phones[r].phone_features;
		
		var has_all_features = false;
		
		
		for(ff=0;ff<tmpFeatures.length;++ff){
		
			if(jQuery.inArray(tmpFeatures[ff], tmpPhone ) != -1){
			
				has_all_features = true;
			
			}
			else{
			
				has_all_features = false;
				break;
			
			}
		
		
		}
		
		//alert(has_all_features);
		
		if(has_all_features == true){
			tmpPhones.push(phones[r]);
		}
		
		
		
		//tmpPhone = tmpPhone.join(",");
			
			
			
		//alert("tmpPhone " + tmpPhone); ///what's in each phones features list
		
		
		//alert(tmpFeatures);
		
		
		
		/*if (tmpPhone.indexOf(tmpFeatures) != -1) {
			if (promo) {
				if (phones[r].phone_free) tmpPhones.push(phones[r]);
			} else {
				tmpPhones.push(phones[r]);
			}
		}*/
		
		
		
		
	}
	$("#phoneListing").empty();

	//alert(tmpPhones);
	activePhones = tmpPhones;
	displayPage(activePhones);
  }
  
  function displayPage(activePhones) {
  	for (b=0; b<activePhones.length; b++) {
		var phoneContainer = jQuery('<li></li>').addClass('block');
		// Assign a first and last class based on the col number
		if (b % NUM_RESULT_COLS == 0) {
			phoneContainer.addClass('first');
		} 
		if ((b+1) % NUM_RESULT_COLS == 0) {
			phoneContainer.addClass('last');
		}

//alert(activePhones[b].phone_name);
		
		var phoneDisplay = jQuery('<div />').addClass('phoneDisplayContainer');



		var phoneThumbContainer = jQuery('<div />').addClass('phoneThumbContainer');


		var phoneLabelContainer = jQuery('<div />').addClass('phoneLabelContainer');
		
		var phoneLabel = jQuery('<span>' + activePhones[b].phone_label + '</span>').addClass('phoneLabel');



		var phoneThumb = jQuery('<img />').addClass('phoneThumb').attr("alt", activePhones[b].phone_name).attr("src", IMAGE_PATH + activePhones[b].phone_thumb) ;


                 var phoneThumbLink = jQuery('<a/>').attr("href","http://www.virginmobileusa.com/phones/phoneDetail.do?skuId=" + activePhones[b].phone_link);


		phoneThumb.appendTo(phoneThumbLink);

		var phone360Container =jQuery('<div />');
		
		

		if(activePhones[b].phone_360_dimensions[0] != 0){
				
					var phone360Image = jQuery('<img />').attr("src", "http://web.virginmobileusa.com/files/phones/small-360").attr("border","0").attr("id",activePhones[b].phone_link).css("cursor","pointer");
		
					windowDimensions[activePhones[b].phone_link] = [activePhones[b].phone_360_dimensions[0],activePhones[b].phone_360_dimensions[1]];
		
		
					phone360Image.bind('click', function() {
					//alert(windowDimensions.length);
					window.open('http://web.virginmobileusa.com/phones/' + this.id + '-360', 'picwindow', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width='+ windowDimensions[this.id][0] +',height='+ windowDimensions[this.id][1] + ',left=50,top=50');
					//return false;
					});
				}
		
		
				var phoneDetailContainer = jQuery('<div />').addClass('phoneDetailContainer');
				
				
				var phoneName = jQuery('<h3>' + activePhones[b].phone_name + '</h3>');
				
				if(activePhones[b].phone_name == "Samsung Mantra"){
				
					phoneName = jQuery('<h3>Samsung Mantra<sup style="font-size:6px">TM</sup></h3>');
				}
                
                if(activePhones[b].phone_name == "Red Slice"){
				
					phoneName = jQuery('<span style="font-size:10px;color:#cc0000;font-weight:bold;text-transform:uppercase;padding:0px;margin:0px;">Special Edition</span><h3 style="margin:0px 0px 5px 0px">Red Slice</h3>');
				}
				
				var phonePrice = jQuery('<h4>' + CURRENCY_LABEL + activePhones[b].phone_price +'</h4>');
				
				var phonePricePromo = jQuery('<div/>');
				
				var phonePromoExpires = jQuery('<span/>');
				
				//alert(phonePricePromo);
				
				if(activePhones[b].phone_price != activePhones[b].phone_before_price){
				
					phonePrice = jQuery('<h4 style="margin-bottom:0px">' + CURRENCY_LABEL + activePhones[b].phone_before_price +  " " + CURRENCY_LABEL + activePhones[b].phone_price +'</h4>');
					
					if(activePhones[b].phone_markdown == "temporary"){
					
						phonePromoExpires = jQuery('<span style="text-transform:uppercase;font-size:10px;font-weight:bold;color:#cc0000">Offer good until ' + activePhones[b].phone_offer_expires + '</span>');
					}
					
					
					phonePricePromo = jQuery('<div style=\"position:absolute;top:16px;left:70px;background:url(http://web.virginmobileusa.com/files/phones/now-slash) no-repeat 0 0;width:104px;height:39px\"></div>');
				
				
				
				}
				var ul = jQuery("<ul></ul>").addClass('features');;
				
				for (c=0; c<activePhones[b].phone_features.length; c++) {
					var featureId = activePhones[b].phone_features[c];
					
					for(d=0; d<features.length; d++) {
						if (features[d].feature_id == featureId) {
							var li = jQuery("<li>" + features[d].feature_name + "</li>");
							li.appendTo(ul);
						}
					if (c >= (FEATURE_LIMIT - 1)) c=100;		
					}
				}
		
		               var phoneSeeDetails = jQuery("<div></div>").addClass('view_details');
		
				var phoneDetailsLink=jQuery('<a> DETAILS</a>').addClass('view_details').attr("href","http://www.virginmobileusa.com/phones/phoneDetail.do?skuId=" + activePhones[b].phone_link);
		
		
				phoneDetailsLink.appendTo(phoneSeeDetails);
		
				var phoneBuy = jQuery("<div></div>").addClass('buy_now');
		
		               
				var phoneLink = 0;
				
				if(activePhones[b].phone_stock != false){
				
					
					phoneLink = jQuery('<a><img src="http://web.virginmobileusa.com/files/phones/buy-now-small"/></a>').addClass('buy_now').attr("href","http://www.virginmobileusa.com/phones/catalogPurchase.do?sku=" + activePhones[b].phone_sku + "&quantity=1");

				}
				
				else{
					
					if(activePhones[b].phone_label == "MORE COLORS"){
					
						
						phoneLink = jQuery('<span>More Colors Available</span>').addClass('buy_now');
						
					
					}
					
					
					else{
						
						if(activePhones[b].phone_name == "X-tc"){
						
							phoneLink = jQuery('<img src="http://web.virginmobileusa.com/files/phones/xtc-out-of-stock"/>').addClass('buy_now');
						}
						
						else{
							phoneLink = jQuery('<span>OUT OF STOCK</span>').addClass('buy_now');
						}
					}
				}
				
		 		//alert(activePhones[b].phone_price - activePhones[b].phone_airtime); 
		
				phoneLink.appendTo(phoneBuy);
				
				var promoContainer = jQuery('<div>' + PROMO_LABEL + '</div>').addClass('phonePromo');
				
				// Build Photo
				phoneLabel.appendTo(phoneLabelContainer);
				
				if(activePhones[b].phone_label != ""){
				
					phoneLabelContainer.appendTo(phoneThumbContainer);
				}
		
				phoneThumbLink.appendTo(phoneThumbContainer);
		
				if(activePhones[b].phone_360_dimensions[0] != 0){
					phone360Image.appendTo(phone360Container);
				
		
					phone360Container.appendTo(phoneThumbContainer);
				}
				
				// Build Phone Details
				phoneName.appendTo(phoneDetailContainer);	
				
				phonePricePromo.appendTo(phoneDetailContainer);
				
				
				
				
				phonePrice.appendTo(phoneDetailContainer); // Price
				
				phonePromoExpires.appendTo(phoneDetailContainer);
				
				ul.appendTo(phoneDetailContainer); // Features
				phoneSeeDetails.appendTo(phoneDetailContainer); // Details Link
				phoneBuy.appendTo(phoneDetailContainer); // Phone Link
				
				// Assemble image, details and promo to displayDiv
				phoneThumbContainer.appendTo(phoneDisplay);
				phoneDetailContainer.appendTo(phoneDisplay);
				phoneDisplay.appendTo(phoneContainer);
				
				// If active promo display promo display
				if (activePhones[b].phone_free) {
					promoContainer.appendTo(phoneContainer); // If free promo, attach display
				}
				else{
				
					if (activePhones[b].phone_deal) {
				
				
					promoContainer = jQuery('<div>Includes $' + activePhones[b].phone_airtime + ' Bonus Airtime</div>').addClass('phonePromo');
					promoContainer.appendTo(phoneContainer); // If free promo, attach display
					}
				}
				
				phoneContainer.appendTo("#phoneListing");
			}
		
}