/*++++++++++++++++++++++++++++++++++

scripts.df.phone_gallery.js

++++++++++++++++++++++++++++++++++*/  

var phone_gallery_arr = new Array();
var phone_gallery_active_feature_count = 0;
var phone_gallery_type_previous = "";
var phone_gallery_fadeout_complete = false;
var phone_gallery_search_array = new Array();
var phone_gallery_search_update = false;
var phone_gallery_sort_default = 'price';
var phone_gallery_sort_new = 'popular';
var phone_gallery_search_noresults;
var phone_gallery_manufacturer_previous = ""; 
var shop_compare_btn_action = "/df/shop/compare.jsp"; // the JSP or page that gets hit when the compare button is enabled.
var shop_compare_text = '<img src="/images/buttons/compare_now.png" class="rollover" alt="Compare Now" />'; // Text for the compare now button
var shop_compare_cookie_duration = 7; // the length of time to keep the cookie stored in days
var shop_compare_no_of_phones = 4; // the max number of phones that we can compare
var shop_compare_connection_type = "";                                                                                            
var shop_compare_inactive_phone_icon = "/images/design/shop_compare_phone_inactive.png"; // the inactive phone icon for the widget
var shop_compare_connection_type = "";
var sorted_array = [];     

var phone_search_suggestions_ajax_call = "/utility/shop/SearchSuggestions.shtml";
var phone_search_results_ajax_call = "/utility/shop/SearchResults.shtml";       

// var phone_search_suggestions_ajax_call = "ajax_search_suggestions.html";
// var phone_search_results_ajax_call = "ajax_search_results.html";

       
$(function() {
	if ($('#phone-filter').length) {
		observeGalleryHandsetAdvisoryTool();
	}         
	
	if ($('.module-phonegallery').length) {
		observeGalleryHover();
	}       
	
	if ($('.module-phonegallery .compare').length) {
		observeCompare();
	}
	
	if ($('.module-phonegallery .compare input').length) {
		loadCompare();
	}
 

   // product lightboxes
   // if (($(".view-details a[rel!='']").length) && (!is_ie6)) {
   // 	setupProductPageLightboxes(".view-details a.dark-btn, .view-details a.light-btn, .module-phonegallery-inner>h2>a, .phone-image a");
   // }

});


function observeGalleryHandsetAdvisoryTool() {
	
	// Help show/hide
	//observePhoneFeaturesHelp();
	                                                                                                                
    // fix the total number of phones
	$("#showing-phones #filtered-phone-total, #showing-phones #phone-total").html($('.module-phonegallery').length);
	
	
	// load the data in each handset into an array
	if ($(".module-phonegallery").length) {
		// array1 = $(".module-phonegallery").attr("class");
		$.each($(".module-phonegallery"), function(){
			tmp_arr = [];
			tmp_arr.push($(this).attr("id"));
			c = $(this).attr("class");
			c_arr = c.split(' ');
			for (var i = 0; i < c_arr.length; i++) {
				phone_property = jQuery.trim(c_arr[i]);
				if (phone_property) {
					tmp_arr.push(phone_property);
				}
			}
			phone_gallery_arr.push(tmp_arr);
		});
	}
	
	// Tabs	
	if ($('#phone-gallery-tabs').length) {
		$('#phone-gallery-tabs a').unbind();
		$('#phone-gallery-tabs a').click(function(){
			if (!$(this).parent('li').hasClass('active')) {
				$(this).parent('li').addClass('active').addClass('subset-active');
				$(this).parent('li').siblings('li.active').removeClass('active').removeClass('subset-active');
			}
			t = $(this).children("span").html().replace( /\s/g, "" );
			GAT("/phonegallery/tab-" + t + "/"); 
			return false;
		});
	}
	
	$.each($("select#sort_phones option"), function(){
		if ($(this).attr('value') == 'price') {
			$(this).html('Price (lowest at top)');
		} else if ($(this).attr('value') == 'batterylife') {
			$(this).html('Battery life (longest life at top)');
		} else if ($(this).attr('value') == 'weight') {
			$(this).html('Weight (lightest at top)');
		} else if ($(this).attr('value') == 'screensize') {
			$(this).html('Screen size (biggest at top)');
		} else if ($(this).attr('value') == 'ratings') {
			$(this).html('Ratings (high to low)');
		} else if ($(this).attr('value') == 'popular') {
			$(this).html('Most popular');
			
		}
	});
	
	if (is_ie6) {
		phone_gallery_sort_new = phone_gallery_sort_default;
	} else {
		$('select#sort_phones').change(function(){
			phone_gallery_sort_new = $('select#sort_phones').val();
		});         
	}

	$("#filter-manufacturer>ul>li>a").bind('click', function(){
		if ($(this).attr('rel') == '') {
			$('#filter-manufacturer>ul>li').removeClass('selected');
			$(this).parent('li').addClass('selected');
		} else {
			$('#filter-manufacturer>ul>li:eq(0)').removeClass('selected');
			$(this).parent('li').toggleClass('selected');
			if ($('#filter-manufacturer>ul>li.selected').length == 0) {
				$('#filter-manufacturer>ul>li:eq(0)').addClass('selected');
			}
		}
	});                        
	
	
	$("#filter-phonetype>ul>li>a").bind('click', function(){
		if ($(this).attr('rel') == '') {
			$('#filter-phonetype>ul>li').removeClass('selected');
			$(this).parent('li').addClass('selected');
		} else {
			$('#filter-phonetype>ul>li:eq(0)').removeClass('selected');
			$(this).parent('li').toggleClass('selected');
			if ($('#filter-phonetype>ul>li.selected').length == 0) {
				$('#filter-phonetype>ul>li:eq(0)').addClass('selected');
			}
		}
	});

	$("#filter-features>ul>li>a").bind('click', function(){
		if ($(this).parent('li').hasClass('selected')) {
			$(this).parent('li').removeClass('selected');
		} else {                
			$(this).parent('li').addClass('selected'); 
			if ($(this).attr("rel")) {
				GAT("/phonegallery/features-" + $(this).val() + "/");
			}
		}              
	});
	
		
	// timer function
	$(".module-phonegallery .hidden").remove();
	setInterval("checkHandsetFilter()",200);
	setupPhoneSearchSuggestions();
}

function checkHandsetFilter() {
	// check the list of active filters
    class_array = [];
	update_flag = false;   
	
	tab_filter = "";
	search_array = [];
	var phone_gallery_manufacturer_current = "";
	$.each($("#filter-manufacturer>ul>li.selected>a"), function(){
		if ($(this).attr('rel') != '') {
			phone_gallery_manufacturer_current = phone_gallery_manufacturer_current + '|' +  $(this).attr('rel');
		}
	});
	
	var phone_gallery_type_current = "";
	$.each($("#filter-phonetype>ul>li.selected>a"), function(){ 
		if ($(this).attr('rel') != '') {
			phone_gallery_type_current = phone_gallery_type_current + '|' +  $(this).attr('rel');
		}
	});
	
	$("#filter-phonetype>ul>li.selected a").attr('rel')
	
	if (
		($("#filter-features>ul>li.selected>a").length != phone_gallery_active_feature_count) || 
		(phone_gallery_type_previous != phone_gallery_type_current) || 
		(phone_gallery_search_update == true) || 
		(phone_gallery_sort_default != phone_gallery_sort_new) || 
		(phone_gallery_manufacturer_previous != phone_gallery_manufacturer_current)
		) {
		
		// zero results
		if (phone_gallery_search_update == true) {
			update_type = 'search';
		} else if (($("#filter-features>ul>li.selected>a").length != phone_gallery_active_feature_count)) {
			update_type = 'features';
		} else if (phone_gallery_type_previous != phone_gallery_type_current) {
			update_type = 'type';
		} else if (phone_gallery_manufacturer_previous != phone_gallery_manufacturer_current) {
			update_type = 'manufacturer';
		} else {
			update_type = '';
		}
		                   
		if ($("#filter-features>ul>li.selected>a").length > 2) {
			$('#clear-all-features').show();
		} else {
			$('#clear-all-features').hide();
		}
		
		phone_gallery_search_update = false;
    	$(".module-phonegallery").hide();
	    
	    // browser check (IE6 has performance issues with sorting)
		
		if (!is_ie6) {
		
	   	 if (phone_gallery_sort_default != $("select#sort_phones").val()) {
				// resort the phones
				phone_gallery_sort_default = $("select#sort_phones").val();
				GAT("/phonegallery/sort-" + phone_gallery_sort_default.replace( /\s/g, "" ) + "/");
			   // alert(phone_gallery_arr);
				if (!sorted_array.length) {
					// only do this once.
				   // alert(phone_gallery_arr.length);
					for (var i = 0; i < phone_gallery_arr.length; i++) { 
						tmp_arr = new Array();
						tmp_arr['product_id'] = phone_gallery_arr[i][0];
						for (j = 1; j < phone_gallery_arr[i].length; j++) {
							var tmp_value = phone_gallery_arr[i][j];
				  //  		alert(tmp_value);
							if (tmp_value.indexOf("filter_sort_price") > -1) {
								tmp_arr['price'] = parseFloat(tmp_value.substring(19, (tmp_value.length -2)));
							} else if (tmp_value.indexOf("filter_sort_batterylife") > -1) {
								tmp_arr['batterylife'] = parseFloat(tmp_value.substring(25, (tmp_value.length -2)));
							} else if (tmp_value.indexOf("filter_sort_weight") > -1) { 
								tmp_arr['weight'] = parseFloat(tmp_value.substring(20, (tmp_value.length -2)));
							} else if (tmp_value.indexOf("filter_sort_screensize") > -1) {                      
								tmp_arr['screensize'] = parseFloat(tmp_value.substring(24, (tmp_value.length -2)));
							} else if (tmp_value.indexOf("filter_sort_ratings") > -1) {
								tmp_arr['ratings'] = parseFloat(tmp_value.substring(21, (tmp_value.length -2)));
							} else if (tmp_value.indexOf("filter_sort_popular") > -1) {
								tmp_arr['popular'] = parseFloat(tmp_value.substring(21, (tmp_value.length -2)));
							}
						
				 //   		alert('price: ' + tmp_arr['price']);
				 //   		alert('popular: ' + tmp_arr['popular']);
						
						}
				    	sorted_array.push(tmp_arr);
					}
				
				}
			
				if (phone_gallery_sort_default == 'price') {
					sorted_array.sort(sortByPrice);
				} else if (phone_gallery_sort_default == 'batterylife') {
					sorted_array.sort(sortByBatterylife);
				} else if (phone_gallery_sort_default == 'weight') {
					sorted_array.sort(sortByWeight);
				} else if (phone_gallery_sort_default == 'screensize') {
					sorted_array.sort(sortByScreenSize);
				} else if (phone_gallery_sort_default == 'ratings') {
					sorted_array.sort(sortByRatings);
				} else if (phone_gallery_sort_default == 'popular') {
				    sorted_array.sort(sortByPrice);
					sorted_array.sort(sortByMostPopular);
				}   
		    
			
			
				// move the appropriate divs around
			    for (var s = 0; s < sorted_array.length; s++) {
					$("#" + sorted_array[s]['product_id']).appendTo("#product-gallery");
				}
		    
				$('#product-gallery .content-footer').appendTo("#product-gallery");
			
		    
			} 
		}
		                    
	    phone_gallery_active_feature_count = $("#filter-features>ul>li.selected>a").length;
	    
		$.each($("#filter-features>ul>li.selected a"), function(){
			class_array.push('filter_feature--' + $(this).attr('rel') + '--');
		});
		
		                            
        phone_gallery_manufacturer_previous = "";    
        $.each($("#filter-manufacturer>ul>li.selected>a"), function(){
       	   if ($(this).attr('rel') != "") {
    			class_array.push("filter_sort_manufacturer--" + $(this).attr('rel') + "--");
    			phone_gallery_manufacturer_previous = phone_gallery_manufacturer_previous + '|' +  $(this).attr('rel');
			}
		});
		                     
		phone_gallery_type_previous = ""; 
	    $.each($("#filter-phonetype>ul>li.selected>a"), function(){  
			if ($(this).attr('rel') != "") {
    			class_array.push("filter_cat_" + $(this).attr('rel'));
    			phone_gallery_type_previous = phone_gallery_type_previous + '|' +  $(this).attr('rel');
			} 
		});
		
		search_array = phone_gallery_search_array;
		
		if ((class_array.length == 0) && ($("#phone_search").val() == "") && (tab_filter == "") && (phone_gallery_manufacturer_previous == "")) {
			resetHandsetFilter();
		}
		
		showHidePhones(search_array, class_array, update_type);
		
		if ($('#filter-features li.selected').length || (!$('#filter-phonetype li:eq(0)').hasClass('selected')) || ($('#filter-search input#phone_search').val() != '')) {
			// feature is active
			$('#phone-filter #show-features a').addClass('feature-star');
		} else {                                                         
		    $('#phone-filter #show-features a').removeClass('feature-star');
		}
	    
	}	
}

function resetHandsetFilterAndUseFeatures() {
	resetHandsetFilter();
	$("#phonefilter-tabs ul li").removeClass("active");
	$("#phonefilter-tabs ul li:eq(1)").addClass("active");
	$("#tab-show-phones-that-have").show();
}

function resetHandsetFilter() {
	$(".module-phonegallery:visible").hide();
	$(".module-phonegallery").fadeIn(400);
	$("#filter-phonetype>ul>li.selected, #filter-manufacturer>ul>li.selected").removeClass("selected");
	$("#filter-phonetype>ul>li:first, #filter-manufacturer>ul>li:first").addClass("selected");
	$("#filter-features>ul>li.selected").removeClass("selected");
	phone_gallery_search_array = new Array();
	$("#phone_search").val("");
	$("#phone-search-reset").remove();
	current_suggestion_index = -1;
	$("#showing-phones #filtered-phone-total").html($(".module-phonegallery").length);    
	$('#no-handsets-match').remove();    
}



function sortByPrice(a,b) {
	tmp_a = a['price'];                                       
	tmp_b = b['price'];                                     
	if (tmp_a < tmp_b) return -1;
	if (tmp_a > tmp_b) return 1;
	return 0;
}


function sortByBatterylife(a,b) {
	tmp_a = a['batterylife'];                                  
	tmp_b = b['batterylife'];;
	if (tmp_a > tmp_b) return -1;
	if (tmp_a < tmp_b) return 1;
	return 0;
}

function sortByWeight(a, b) {
	tmp_a = a['weight'];                                          
	tmp_b = b['weight'];                                          
	if (tmp_a < tmp_b) return -1;
	if (tmp_a > tmp_b) return 1;
	return 0;
}

function sortByScreenSize(a,b) {
	tmp_a = a['screensize'];                                
	tmp_b = b['screensize'];                                 
	if (tmp_a > tmp_b) return -1;
	if (tmp_a < tmp_b) return 1;
	return 0;
}

function sortByRatings(a,b) {
	tmp_a = a['ratings'];                                 
	tmp_b = b['ratings'];                                 
	if (tmp_a > tmp_b) return -1;
	if (tmp_a < tmp_b) return 1;
	return 0;
} 

function sortByMostPopular(a,b) {
	tmp_a = a['popular'];                                      
	tmp_b = b['popular'];                                   
	if (tmp_a > tmp_b) return -1;
	if (tmp_a < tmp_b) return 1;
	return 0;
}



function showHidePhones(a_ids, a_classes, update_type) {   
	show_list = new Array();
	for (var i = 0; i < phone_gallery_arr.length; i++) {	
		class_counter = 0;		
		for (j = 1; j < phone_gallery_arr[i].length; j++) {
		   	
			if (jQuery.inArray(phone_gallery_arr[i][j], a_classes) > -1) {
				if (phone_gallery_arr[i][j].indexOf('filter_sort_manufacturer') > -1) {
                 	class_counter = class_counter + ($('#filter-manufacturer ul li.selected').length);
				} else if (phone_gallery_arr[i][j].indexOf('filter_cat_') > -1) {
				    class_counter = class_counter + ($('#filter-phonetype ul li.selected').length);
				} else {
                	class_counter = class_counter + 1;
				}
			}
			
		}
		if ((class_counter == a_classes.length) && (class_counter != 0)) {
			show_list.push(phone_gallery_arr[i][0]); 			
		}		
		
		
		   	
	}
	
	if (a_classes.length) {
		if (a_ids.length > 0) {
			show_list2 = [];
			for (var x = 0; x < a_ids.length; x++) {
				if (jQuery.inArray(a_ids[x], show_list) > -1) {
					show_list2.push(a_ids[x]);
				}
			}
			show_list = show_list2;
		}
	} else if ((a_ids.length) && (phone_gallery_search_noresults == false)) {
		show_list = a_ids;
	}
	
	if ($("#no-handsets-match").length) {
		$("#no-handsets-match").remove();
	}
	
	if (show_list.length > 0) {
		for (var k = 0; k < show_list.length; k++) {
			$("#" + show_list[k]).fadeIn(400);
		}
		$("#showing-phones #filtered-phone-total").html(show_list.length);
	} else if ((a_classes.length == 0) && ($("#phone_search").val() == "")) {
		$("#showing-phones #filtered-phone-total").html(phone_gallery_arr.length);
	} else {
		if (update_type == 'search') {
			// search msg
			zero_results_msg = '<div class="filter-empty" id="no-handsets-match" style="display: none"><h2>No phones found</h2><p>Your search - <strong>' + $("#phone_search").val() + '</strong> - did not match any phones</p><p><a href="javascript:resetPhoneSearch();">Clear your search and start over</a>.</p></div>';
		} else if (update_type = 'features') {
			// features msg
			zero_results_msg = '<div class="filter-empty" id="no-handsets-match" style="display: none"><h2>No phones found</h2><p>Try unselecting some of the options your chose, or <a href="javascript:resetHandsetFilter();">clear your selections and start again</a>.</p></div>';
		} else if (update_type = 'tabs') {
			// tabs msg
			zero_results_msg = '<div class="filter-empty" id="no-handsets-match" style="display: none"><h2>No phones found</h2><p>Try selecting a different tab.</p></div>';
			
		}
		$("#showing-phones #filtered-phone-total").html("0");
		// show that tab message
		$("#product-gallery").append(zero_results_msg);
		$("#no-handsets-match").fadeIn(400);
	}
}

function resetFilters() {
	$('#filter-features ul li').removeClass('selected');
}          

function viewFeaturesExplained(){
	if ($('.features-explained-text-visible').length) {
		$('.features-explained-text-wrapper').hide();
	} else {
		$('.features-explained-text-wrapper').addClass('features-explained-text-visible');
	}
	
}
 
function hideFeatures() {
	$('#filter-expanded').slideUp();
	$('#hide-features').slideUp();
	$('#show-features').slideDown();
	$('#phone-filter-wrapper').removeClass('phone-filter-wrapper-expanded');
}   

function showFeatures() {
	$('#filter-expanded').slideDown();
	$('#hide-features').slideDown();
	$('#show-features').slideUp();
	$('#phone-filter-wrapper').addClass('phone-filter-wrapper-expanded');
} 

function observeGalleryHover() {
  
  if($('#product-gallery.my-way-product-gallery').length) {
    
    $('.module-phonegallery').bind('mouseenter', function(){
  		$(this).addClass('module-phonegallery-hover');
  		var id = $(this).attr('id');
  		$('#' + id + ' .select-phone a.darkbtn').addClass('green-btn').removeClass('dark-btn');
  	});
  	
  	$('.module-phonegallery').bind('mouseleave', function(){
  		$(this).removeClass('module-phonegallery-hover');                                       
  		var id = $(this).attr('id');
  		$('#' + id + ' .select-phone a.darkbtn').addClass('dark-btn').removeClass('green-btn');
  	});
    
  }
  else {
  	$('.module-phonegallery').bind('mouseenter', function(){
  		$(this).addClass('module-phonegallery-hover');
  		var id = $(this).attr('id');
  		$('#' + id + ' .view-details a.darkbtn').addClass('green-btn').removeClass('dark-btn');
  	});

  	$('.module-phonegallery').bind('mouseleave', function(){
  		$(this).removeClass('module-phonegallery-hover');                                       
  		var id = $(this).attr('id');
  		$('#' + id + ' .view-details a.darkbtn').addClass('dark-btn').removeClass('green-btn');
  	});    
  }
  

} 
    
/* phone search suggestions */

function setupPhoneSearchSuggestions() {
	// start
	$('#phone_search').focus(function(){
		setInterval("checkForPhoneSearchEntries()",100);
		$(window).keydown(function(event){
			if (event.keyCode == 40) {
				return false;
			}
		});
	});
	
	$('#phone_search').keydown(function(event){
		global_phone_search = true;
		total_suggestions = $('#filter-search #phone-suggestions li').length;
		if (total_suggestions) {
			if (event.keyCode == 40) {
				current_suggestion_index = current_suggestion_index +1;
				if (current_suggestion_index >= total_suggestions) {
					current_suggestion_index = -1;
				}
				setPhoneSuggestionFocus(current_suggestion_index);
			} else if (event.keyCode == 38) {
				current_suggestion_index = current_suggestion_index -1;
				if (current_suggestion_index <= -2) {
					current_suggestion_index = total_suggestions -1;
				}
				setPhoneSuggestionFocus(current_suggestion_index);
			}
		}
	});

	$('#phone_search').blur(function(){
		clearInterval();
		phone_gallery_search_timer  = setTimeout("$('#phone-search-box #phone-suggestions').remove()", 300);
	});
	
	$('#filter-search #phone-suggestions').bind("mouseover", function(){
		clearTimeout(phone_gallery_search_timer);
	});

}

function setPhoneSuggestionFocus(i) {
	$('#filter-search #phone-suggestions li').removeClass('highlighted');
	if (i == -1) {
		$('#phone_search').focus();
	} else {
		$('#filter-search #phone-suggestions li:eq(' + i + ')').addClass('highlighted');
	}
}

function checkForPhoneSearchEntries() {
		if ($('#phone_search').val() == '') {
			$('#filter-search #phone-suggestions').remove();
			current_suggestion_text = $('#phone_search').val();
		} else if ($('#phone_search').val() != current_suggestion_text) {
			current_suggestion_text = $('#phone_search').val();
			if ($("input#onlinechannel").length) {
				w = $("input#onlinechannel").val();
			} else {
				w = "";
			}
			$.ajax({
				type: "GET",
				url: phone_search_suggestions_ajax_call,
				data: "q=" + current_suggestion_text + "&w=" + w,
				success: function(msg){
					
					$('#filter-search #phone-suggestions').remove();
					if (msg != "") {
					//	alert(msg);
						$('#filter-search').append('<div id="phone-suggestions">' + msg + '</div>');
					    $('#phone-suggestions').bgiframe();
						$('#filter-search #phone-suggestions li a').bind('click', function() {
							product_arr_a = this.href.split("#products[");
							product_arr_b = product_arr_a[product_arr_a.length -1].split("]");
							product_arr_c = product_arr_b[0].split(";");
							phone_gallery_search_array = new Array();
							if (product_arr_c.length) {
								for (var l = 0; l < product_arr_c.length; l++) {
									phone_gallery_search_array.push('product_' + product_arr_c[l]);
								}
							}
							$('#filter-search #phone_search').val($(this).html());
							current_suggestion_text = $(this).html();
							$('#filter-search #phone-suggestions').remove();
							phone_gallery_search_update = true;
							phone_gallery_search_noresults = false;  
							return false;
						});
					}
				}
			});
		}
}

function submitPhoneSearch() {
	clearInterval(); 
	if ($('#filter-search #phone-suggestions li.highlighted').length) {
		current_suggestion_text = $('#filter-search #phone-suggestions li.highlighted a').html();
		GAT("/phonegallery/index.jsp?handset-search=" + current_suggestion_text);
		$("#phone_search").val($('#filter-search #phone-suggestions li.highlighted a').html());
		product_arr_a = $('#filter-search #phone-suggestions li.highlighted a').attr('href').split('#products[');
		product_arr_b = product_arr_a[product_arr_a.length -1].split("]");
		product_arr_c = product_arr_b[0].split(";");
		if (product_arr_c.length) {
			for (var l = 0; l < product_arr_c.length; l++) {
				phone_gallery_search_array.push('product_' + product_arr_c[l]);
			}
		}
		phone_gallery_search_update = true;		
		phone_gallery_search_noresults = false;
		$('#filter-search #phone_search').val($('#filter-search #phone-suggestions li.highlighted a').html());
		$('#filter-search #phone-suggestions').remove();
	} else {
		// Ajax request to get all phones matching
		if ($("input#onlinechannel").length) {
			w = $("input#onlinechannel").val();
		} else {
			w = "";
		}
		
		GAT("/phonegallery/index.jsp?handset-search=" + current_suggestion_text);
	    
		$.ajax({
			type: "GET",
			url: phone_search_results_ajax_call,
			data: "q=" + current_suggestion_text + "&w=" + w,
			success: function(msg){
				msg = jQuery.trim(msg);
				if (msg != "") {
					product_arr = msg.split(";");
				} else {
					product_arr = [];
				}
				phone_gallery_search_array = new Array();
				if (product_arr.length) {
					for (var l = 0; l < product_arr.length; l++) {
						phone_gallery_search_array.push('product_' + product_arr[l]);
					}
					phone_gallery_search_noresults = false;
				} else {
					phone_gallery_search_noresults = true;
				}
				phone_gallery_search_update = true; 
				$('#filter-search #phone-suggestions').remove();
			}
		});
	} 
}  
   

/* Compare functions */

function loadCompare() {                                                         
	$.cookie('shop_phones_compare', '', {expires: shop_compare_cookie_duration});
	$.each($('.module-phonegallery .compare input:checked'), function(){
		if ($(".footer .compare").length) { 
			var v = $(this).val() + '|' + $(this).parent('.compare').parent('.footer').parent('.module-phonegallery-inner').children('.phone-image').children('a').children('img').attr('src');
		} else {
			var v = $(this).val() + '|' + $(this).parent('.compare').parent('.module-phonegallery-inner').children('.phone-image').children('a').children('img').attr('src');
		}                                                        
		var cookie_array = cookieToArray('shop_phones_compare');
		cookie_array = $.merge(cookie_array, [v]);
		arrayToCookie(cookie_array,'shop_phones_compare');
		if ($(".footer .compare").length) {
			$(this).parent('.compare').parent('.footer').parent('.module-phonegallery-inner').parent('.module-phonegallery').addClass('module-phonegallery-compare'); 
		} else {
			$(this).parent('.compare').parent('.module-phonegallery-inner').parent('.module-phonegallery').addClass('module-phonegallery-compare'); 
		}
		$('.module-phonegallery-compare .compare a').remove();
		$('.module-phonegallery-compare .compare label').html('').after('<a href="' + compareURL() + '">compare phones</a>');                                                                                                                        
		if (cookie_array.length == 4) {
		   $('.module-phonegallery .compare input[type=checkbox]').not(':checked').attr('disabled', 'disabled').parent('.compare').addClass('compare-disabled'); 
		}
	});
	updateCompareWidget()
}


function observeCompare() {
	shop_compare_connection_type = $('#connection-type').val();
	if ($.cookie('shop_compare_connection_type')) {
		if ($.cookie('shop_compare_connection_type') != shop_compare_connection_type) {
			$.cookie('shop_compare_connection_type', shop_compare_connection_type, {expires: shop_compare_cookie_duration});
			$.cookie('shop_phones_compare', '', {expires: shop_compare_cookie_duration});
		}
	} else {
		$.cookie('shop_compare_connection_type', shop_compare_connection_type, {expires: shop_compare_cookie_duration});
	}
	$('.module-phonegallery .compare input').bind('click', togglePhoneToCompare);
}
    
function togglePhoneToCompare() {
	if ($(".footer .compare").length) {
		var v = $(this).val() + '|' + $(this).parent('.compare').parent('.footer').parent('.module-phonegallery-inner').children('.phone-image').children('a').children('img').attr('src');
	} else {
		var v = $(this).val() + '|' + $(this).parent('.compare').parent('.module-phonegallery-inner').children('.phone-image').children('a').children('img').attr('src');
	}
	if (this.checked == true) { 
		if (!$.cookie('shop_phones_compare')) {
			$.cookie('shop_phones_compare', v, {expires: shop_compare_cookie_duration});
			var cookie_array = cookieToArray('shop_phones_compare');
		} else {
			var cookie_array = cookieToArray('shop_phones_compare');
			if (cookie_array.length < shop_compare_no_of_phones) {
				cookie_array = $.merge(cookie_array, [v]);
				arrayToCookie(cookie_array,'shop_phones_compare');
			}
		}
		if ($(".footer .compare").length) {
			$(this).parent('.compare').parent('.footer').parent('.module-phonegallery-inner').parent('.module-phonegallery').addClass('module-phonegallery-compare'); 
		} else {   
			$(this).parent('.compare').parent('.module-phonegallery-inner').parent('.module-phonegallery').addClass('module-phonegallery-compare'); 
		}
		$('.module-phonegallery-compare .compare a').remove();
		$('.module-phonegallery-compare .compare label').html('').after('<a href="' + compareURL() + '">compare phones</a>');
		if (cookie_array.length == 4) {
		   $('.module-phonegallery .compare input[type=checkbox]').not(':checked').attr('disabled', 'disabled').parent('.compare').addClass('compare-disabled'); 
		}
		
	} else {
		if ($.cookie('shop_phones_compare')) {
			var cookie_array = cookieToArray('shop_phones_compare');
			var new_cookie_array = new Array();
			for (var i = 0; i < cookie_array.length; i++) {
				if (cookie_array[i] != v) {
					new_cookie_array.push(cookie_array[i]);
				}                                          
			}
			arrayToCookie(new_cookie_array,'shop_phones_compare'); 
		}
		if ($(".footer .compare").length) {                                                          
			$(this).parent('.compare').parent('.footer').parent('.module-phonegallery-inner').parent('.module-phonegallery').removeClass('module-phonegallery-compare');
		} else {
			$(this).parent('.compare').parent('.module-phonegallery-inner').parent('.module-phonegallery').removeClass('module-phonegallery-compare');
		}
		
		$(this).parent('.compare').children('label').html('Add to compare'); 
		$(this).parent('.compare').children('a').remove(); 
		if (cookie_array.length = 3) {
		   $('.module-phonegallery .compare input[type=checkbox]').not(':checked').attr('disabled', '').parent('.compare').removeClass('compare-disabled'); 
		}
	}
	
	updateCompareWidget();
}       

function compareURL() {
	compare_cookie_val = '';
	if ($.cookie('shop_phones_compare')) {
		var cookie_array = cookieToArray('shop_phones_compare');
		for (var i = 0; i < cookie_array.length; i++) {
			var productids = cookie_array[i].split('|');
			if (compare_cookie_val) {
				compare_cookie_val = compare_cookie_val + ';';  
			}
			compare_cookie_val = compare_cookie_val +  productids[0]; 
		}
	}                  
	     
	return shop_compare_btn_action + '?compare=' + compare_cookie_val + '&connection=' + $('#connection-type').val();
}        

function updateCompareWidget() {
	if ($('.module-phonegallery-compare').length > 1) {
		$('#compare-btn').show();
		$('#compare-text').hide();
		$('#compare-btn a').attr('href', compareURL());
	} else {
		$('#compare-btn').hide(); 
		$('#compare-text').show();
		$('#compare-btn a').attr('href', 'javascript:;');
	}
	
	var cookie_array = cookieToArray('shop_phones_compare');         
	$('#nav_comparephones h2 span strong').html(cookie_array.length);
	if ((cookie_array.length > 0) && ($('#nav_comparephones').hasClass('closed-accordian'))) {
	   toggleAccordian('nav_comparephones');
	}
	var total_blank_compare = $('#compare-phones .phones ul li').length;
	for (var i = 0; i < total_blank_compare; i++) {                  
		if (cookie_array[i]) {
		    var productids = cookie_array[i].split('|');
			img_src = productids[1]; 
		} else {
			img_src = shop_compare_inactive_phone_icon;
		}                       
		                                                          
	 	$('#compare-phones .phones ul li:eq(' + i + ') img').attr('src', img_src);    
    }
}
 

function toggleBuyBusinessPhones() {
	if ($('.business-phones-info').is(":visible")) {
		$('.business-phones-info').slideUp();
		$('#how-to-buy-business-phones .show-hide-toggle a').html('We can look after you from 2 to 50+ phones');
	} else {
	    $('.business-phones-info').slideDown();                                                                 
		$('#how-to-buy-business-phones .show-hide-toggle a').html('hide this');
	
	}
}  

function togglePhoneFilters(){
	$('#phone-filter-wrapper').removeClass('business-phone-filter-wrapper');
	$('#phone-filter-business-toggle').slideDown();
	$('#phone-filter .show-hide-toggle').remove();
}      

function setupProductPageLightboxes(o) {  
   	$(o).bind('click', function(){     
		SWFAddress.setValue($(this).attr('rel'));
		$(this).blur();
		return false;
	});               
   	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handlePhoneGalleryLBChange);  
}
            
function setupProductPageLightboxContent() {
	setTimeout('updatePageSize()', 1000);
	setupButtons('#fancybox-content ');
	setupButtonActions();
	observeProductTabs();
//	setupProductPageLightboxes(".similar-phones-content .button a.lightbtn");
}   

function updatePageSize() {
	var height = parseFloat($(document).height());
	var increased_height = parseFloat($("#fancybox-wrap").height()) + parseFloat($("#fancybox-wrap").css('top')) + 100
	if (height > increased_height) {
		$("#fancybox-overlay").css({
			"height" : height + "px"
		});
	} else {
		$("#fancybox-overlay").css({                        
			"height" : increased_height + "px"
		});
	}
} 
       

// Determines if the Shadowbox should close, or display an image
function handlePhoneGalleryLBChange(event) {	
	if(event.path=='/') {
	    $.fancybox.close();
	} else if (event.path == '/gallery') {
	    $.fancybox.close();
	} else {
	    if (localfile) {
	    	url = SWFAddress.getPath().substr(1) + '?_=' + Math.floor(Math.random()*10000000);
	    } else {
	    	url = SWFAddress.getPath() + '?' + SWFAddress.getQueryString();
	    }   
		                    
		$("#fancybox-overlay").css({
			"background-color":"#000",
			"opacity":"0.6",
			"height":$(document).height()
		}).fadeIn('slow', function(){
		    $.fancybox({
				'transitionIn'	:	'fade',
				'transitionOut'	:	'fade',
				'speedIn'		:	200, 
				'speedOut'		:	0, 
				'overlayShow'	:	true,
				'overlayOpacity':   0.6,
				'overlayColor'	: 	'#000',
				'autoScale'		:   false,
				'padding'		:   0, 
				'titleShow'		: 	false,
				'showNavArrows'	: 	false,
				'onStart'		:   showLightBoxOverlay,
				'onComplete'	: 	setupProductPageLightboxContent,
				'onClosed'		: 	resetSWFAddress,	 
				'href'			:   url
			});
		}); 
	}
}     

function resetSWFAddress() { SWFAddress.setValue('/gallery')  }       

function showLightBoxOverlay() {
	
	
}                                 

