

/**
 * Page Boot strap
 */
$(document).ready(function() {
	if ($('div.resultWindow').length>0){
		jpPhonePriceSlider();
	}
	
	if ($('div.resultWindow').length>0 || $('div.accessoriesArea').length>0){
		jpPhoneFilter();
	}
	
	fixBrandSpecificLinks('en');
	fixBrandSpecificLinks('ar');
	
	//convertLinksToCheckBox();
	//toggleDivs();
});

function fixBrandSpecificLinks(lang)
{
	var searchFor = '/go/' + lang + '/manufacturer/phones/';
	var searchForLength = searchFor.length;
	var newHrefStart = '/go/' + lang + '/phones/allphones/#';
	
	var crappyLink = $('[href*=' + searchFor + ']').each(function(){
		
		var el = $(this);
		var elHref = el.attr('href');
		var startPos = elHref.indexOf(searchFor) + searchForLength;
		var brand = elHref.slice(startPos);
		
		el.attr('href', newHrefStart + brand);
	});
}

function jpPhoneFilter()
{
	jpAnchorsToCheckboxes();
	
	$('.phoneFilterCheckbox').click(handleFilterChange);
	
	$('.accFilterCheckbox').click(toggleAccessories);
	
	if('undefined' != typeof window.location.hash)
	{
		var hash = window.location.hash.slice(1);
		
		var hashBox = $('.brandPhoneFilterCheckbox[value='+hash+']');
		
		if(hashBox.length > 0)
		{
			hashBox.attr('checked', true); //check the relevant box
		
			var allBrandsBox = $('.allBrandsFilterCheckbox'); //get the all brands box
			allBrandsBox.attr('checked', false); //uncheck it
			
			handleFilterChange(hashBox); //manually fire the change event handler
		}
	}
}

function jpPhonePriceSlider()
{
	$("#phonePriceOptions").show();
	$("#phonePriceSlider").slider({
		range: true,
		min: 0,
		max: 5000,
		values: [0, 5000],
		step: 250,
		stop: function(e, ui) {
			handleFilterChange(e);
			$('.phonePriceFrom').text('Min: QR ' + ui.values[0]);
			$('.phonePriceTo').text('Max: QR ' + ui.values[1]);
		},
		slide: function(e, ui) {
			$('.phonePriceFrom').text('Min: QR ' + ui.values[0]);
			$('.phonePriceTo').text('Max: QR ' + ui.values[1]);
		}
	});
	
	$('.phonePriceFrom').text('Min: QR ' + $("#phonePriceSlider").slider("values", 0));
	$('.phonePriceTo').text('Max: QR ' + $("#phonePriceSlider").slider("values", 1));
	
	$('.resetPriceSlider').click(resetPriceSlider);
}

function resetPriceSlider(event)
{
	event.preventDefault();
	$("#phonePriceSlider").slider("values", 0, $("#phonePriceSlider").slider("option", "min"));
	$("#phonePriceSlider").slider("values", 1, $("#phonePriceSlider").slider("option", "max"));
	$('.phonePriceFrom').text('From: QR ' + $("#phonePriceSlider").slider("values", 0));
	$('.phonePriceTo').text('To: QR ' + $("#phonePriceSlider").slider("values", 1));
	handleFilterChange(event);
}

function jpAnchorsToCheckboxes()
{
	$("#allphones").find("a").each(
		function(){
			var txt = $(this).text();
			$(this).replaceWith("<input class='phoneFilterCheckbox allBrandsFilterCheckbox' type='checkbox' checked='checked' value='allBrands' id='input4"+txt+"' /><label for='input4"+txt+"'>"+txt+"</label>");
		}
	);
	
	$("#allfeatures").find("a").each(
		function(){
			var txt = $(this).text();
			$(this).replaceWith("<input class='phoneFilterCheckbox allFeaturesFilterCheckbox' type='checkbox' checked='checked' value='allFeatures' id='input4"+txt+"' /><label for='input4"+txt+"'>"+txt+"</label>");
		}
	);
	
	$("#pmakes").find("a").each(
		function(){
			var txt = $(this).attr("class");
			$(this).replaceWith("<input class='phoneFilterCheckbox brandPhoneFilterCheckbox' type='checkbox' value='"+txt.toLowerCase()+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+$(this).text()+"</label>");
		}
	);
	
	$("#features").find("a").each(
		function(){
			var txt = $(this).attr("class");
			$(this).replaceWith("<input class='phoneFilterCheckbox featurePhoneFilterCheckbox' type='checkbox' value='"+txt.toLowerCase()+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+$(this).text()+"</label>");
		}
	);
	
	$("#allaccessories").find("a").each(
			function(){
				var txt = $(this).text();
				$(this).replaceWith("<input class='accFilterCheckbox' id='allaccess' type='checkbox' checked='checked' value='all' id='input4"+txt+"' /><label for='input4"+txt+"'>"+txt+"</label>"); 
			}
	);
	$("#accessories").find("a").each(
			function(){
				var txt = $(this).text();
				$(this).replaceWith("<input class='accFilterCheckbox' type='checkbox' value='"+$(this).attr("class")+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+txt+"</label>");
			}
	);	
	
	$("div#sortArea").find("input:radio").click(sortPhones);
	
	//reset all link
	$(".searchFilter").find("a").click(function(event){
		
		event.preventDefault();
		$('.brandPhoneFilterCheckbox').attr('checked', false);
		$("#allphones").find("input[type='checkbox']").click();
		resetPriceSlider(event);
	});	
	var promoPhones = $('.promoPhone').detach();
	
	promoPhones.prependTo('#resultArea');
	
}

function handleFilterChange(e)
{	
	
	var priceFrom = $("#phonePriceSlider").slider("values", 0);
	var priceTo = $("#phonePriceSlider").slider("values", 1);
	
	var $target = $(e.target);
	var $targetValue = $target.val()
	/* hide all phones */
	$('.resultWindow').fadeOut("medium");
	
	/* do brands */
	if('allBrands' == $targetValue)
	{
		if($target.attr('checked'))
		{	
			$('.brandPhoneFilterCheckbox').attr('checked', false);
		}
	}

	$checkedBrands = $('.brandPhoneFilterCheckbox:checked');
	var $brandSelector = '';
	if($checkedBrands.length > 0)
	{
		$('.allBrandsFilterCheckbox').attr('checked', false);
		$brandVals = new Array();
		$checkedBrands.each(function(){
			
			$brandVals.push('.' + $(this).val());
		});
		
		$brandSelector = $brandVals.join(', ');
	}
	else	
	{
		$('.allBrandsFilterCheckbox').attr('checked', true);
		$brandSelector = '.resultWindow';
	}

	/* do features */
	if('allFeatures' == $targetValue)
	{
		if($target.attr('checked'))
		{	
			$('.featurePhoneFilterCheckbox').attr('checked', false);
		}
	}
	
	$checkedFeatures = $('.featurePhoneFilterCheckbox:checked');
	var $featureSelector = '';
	if($checkedFeatures.length > 0)
	{
		$('.allFeaturesFilterCheckbox').attr('checked', false);
		$featureVals = new Array();
		$checkedFeatures.each(function(){
			
			$featureVals.push('.' + $(this).val());
		});
		
		$featureSelector = $featureVals.join('');
	}
	else	
	{
		$('.allFeaturesFilterCheckbox').attr('true', false);
		$featureSelector = '.resultWindow';
	}

	/* select phones and show */
	$($brandSelector).each(function(){

		var inPriceRange = false;
		
		var phonePrice = $(this).find('.phonePrice .skipit').text().slice(0, -3);
		if(phonePrice >= priceFrom && phonePrice <= priceTo)
		{
			inPriceRange = true;
		} 
		
		if($(this).is($featureSelector) && inPriceRange)
		{
			$(this).fadeIn("medium");
		}
	});
}




























function convertLinksToCheckBox() {
	$("#allphones, #allfeatures").find("a").each(
			function(){
				var txt = $(this).text();
				$(this).replaceWith("<input type='checkbox' checked='checked' value='"+txt.toLowerCase()+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+txt+"</label>");
			}
	);
	$("#allaccessories").find("a").each(
			function(){
				var txt = $(this).text();
				$(this).replaceWith("<input id='allaccess' type='checkbox' checked='checked' value='"+txt.toLowerCase()+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+txt+"</label>"); 
			}
	);
	$("#accessories").find("a").each(
			function(){
				var txt = $(this).text();
				$(this).replaceWith("<input type='checkbox' value='"+$(this).attr("class")+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+txt+"</label>");
			}
	);	
	$("#pmakes").find("a").each(
			function(){
				var txt = $(this).attr("class");
				$(this).replaceWith("<input type='checkbox' value='"+txt.toLowerCase()+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+$(this).text()+"</label>");
			}
	);
	$("#features").find("a").each(
			function(){
				var txt = $(this).attr("class");
				$(this).replaceWith("<input type='checkbox' value='"+txt.toLowerCase()+"' id='input4"+txt+"' /><label for='input4"+txt+"'>"+$(this).text()+"</label>");
			}
	);
	$("#allphones, #allfeatures").find("input").click(togglePhones);
	$(".searchFilter").find("a").click(function(){
		$("#allphones").find("input[type='checkbox']").click();
	});	
	$("div#sortArea").find("input:radio").click(sortPhones);
	$("#pmakes").find("input:checkbox").click(togglePhones);
	$("#features").find("input:checkbox").click(togglePhones);
	$("#accessories").find("input:checkbox").click(toggleAccessories);
	$("#allaccessories").find("input:checkbox").click(toggleAccessories);
}
/**
*
* @return
*/
function toggleAccessories(event) {
	var all  = $("#allaccessories").find("input[type='checkbox']");
	var selected  = $("#accessories").find("input:checkbox:checked");
	var afilter;
	
	var target = $(event.target);
	if($(target).val() == "all"){
		//console.debug("resetting filters");
		$(selected).each(
			function(){
				$(this).attr("checked", false);
			}
		);		
		selected = $("#pmakes").find("input:checkbox:checked");
		$(all).attr("checked", true);
	}
	
	$(all).attr("checked", (selected.size() > 0) ? 
		function(){
			afilter = _getSelected(selected);
			var sacc = $("#midContentArea").children(afilter.join(","));
			_togglePhone($("#midContentArea").children(".accessoriesArea"), sacc);	
			return false;
		}
	:
		function(){
			//console.debug("all acessories");
			_togglePhone(null, $("#midContentArea").children(".accessoriesArea"));
			return true;
		}
	);//attr
}
/**
 *
 * @return
 */
function sortPhones(event){
	var order  = $(event.target).attr("value");
	var criteria = (order =="rand")? "h2":"span.skipit";
	_sort(criteria, order);
	
}
/**
*
* @return
*/
function _sort(criteria, order){
	if(order != "rand")
		$("div.resultWindow").tsort(criteria, {order:order});
	else
		$("div.resultWindow").tsort(criteria);
}
/**
 * 
 * @return
 */
function togglePhones(event) {
	var allMakes  = $("#allphones").find("input[type='checkbox']");
	var allFeatures  = $("#allfeatures").find("input[type='checkbox']");
	var showMakes = $("#pmakes").find("input:checkbox:checked");
	var features   = $("#features").find("input:checkbox:checked");
	var pfilter;
	var ffilter;
	var selectedPhones;
	
	//var event  = (!event)? window.event:event;
	//var target = (event.target) ? event.target : event.srcElement;
	var target = $(event.target);
	if($(target).val() == "all"){
		//console.debug("resetting filters");
		$(showMakes).each(
			function(){
				$(this).attr("checked", false);
			}
		);
		$(features).each(
				function(){
					$(this).attr("checked", false);
				}
			);		
		showMakes = $("#pmakes").find("input:checkbox:checked");
		features   = $("#features").find("input:checkbox:checked");
		$(allMakes).attr("checked", true);
	}

	$(allMakes).attr("checked", (showMakes.size() > 0) ? 
				//If true
				function(){
					//Find selected items
					pfilter=_getSelected(showMakes);
					ffilter=_getSelected(features);
					if(features.size() == 0){
						//console.debug("Showing selected Phones without features");
						selectedPhones = $("#resultArea").children(pfilter.join(","));
						_togglePhone($("#resultArea").children(".resultWindow"), selectedPhones);	
					}else{
						//console.debug("Showing selected Phones with features");
						selectedPhones = $("#resultArea").children(pfilter.join(","));
						selectedPhones.each(
							function(){
								var phone = $(ffilter.join(","), this);
								if(phone.size() == 0)
									$(this).toggle("medium");
							}
						);
						///_togglePhone($("#resultArea").children(".resultWindow"), selectedPhones);	
					}
					return false;
				} 
				: 
					//If false
				function(){
					//console.debug("Showing all Phones");
					$("#pmakes").find("input[type='checkbox']").attr("checked", false);
					ffilter=_getSelected(features);
					if(features.size() > 0){
						//console.debug("Showing all Phones with features");
						selectedPhones = $("#resultArea").children(".resultWindow");
						selectedPhones.each(
								function(){
									var phone = $(ffilter.join(","), this);
									if(phone.size() == 0)
										$(this).toggle("medium");
								}
						);						
					}else{
						//console.debug("Showing all Phones without features");
						_togglePhone(null, $("#resultArea").children(".resultWindow"));
					}
					return true;
				}
			);
	$(allFeatures).attr("checked" , (features.size() > 0) ? false: true);
	
}
/**
 * Private Method only to be called from elsewhere within this code.
 * @return list of items from selected check boxes
 */
function _getSelected(list){
	//Find selected features
	var selectedItem = [list.size()];
	$(list).each(
		function(i, list){
			selectedItem[i] ="."+$(list).val();
		}
	);	
	return selectedItem;
}
/**
 * Toogles phone visibility
 */
function _togglePhone(hide, show){
	////console.debug(hide);
	//console.debug(show);
	////console.debug(features);
	if(hide != null )
		hide.fadeOut("medium");
	
	show.fadeIn("medium");
}

/**
 * Toggle Divs
 */
function toggleDivs() {
	//console.debug(step);
	var stepshow = "#step"+(step);
	$(stepshow).toggle();
	var tabs = $("#tabs li");
	$(tabs.get(0)).attr("class", "active");

	$("#tabs").find("a").click(function(event){
		var prv = $("#tabcontainer .getNumberContainer");
		$(prv).each(function(){
								$(this).hide();
							 });
		$("#tabs").find("li").each(function(){
											if($(this).attr("class") != "specialTab")
												$(this).attr("class", "");
										});
		
		var target = $(event.target);
		var id = $(target).attr("id")
		var show = "#step"+(id.substring(1));
		var parent = $(target).parent().get(0);
		if($(parent).attr("class") == "")
			$(parent).attr("class", "active");
		$(show).toggle();
		
	});		
}

