// JavaScript Document

$(document).ready(function(){

	function categoryHoverIn(){

		$(this).removeClass('inactive_category');
		$(this).addClass('hover_category');		
		$('.category',this).show();
	}

	function categoryHoverOut(){
		
		$(this).removeClass('hover_category');	
		$(this).addClass('inactive_category');		
		$('.category',this).hide();	
	}
	
	function dropdownHoverIn(){		
		$('.dropdown',this).show();
	}

	function dropdownHoverOut(){	
		$('.dropdown',this).hide();	
	}
	
	var categoryConfig ={
		over: categoryHoverIn,
		timeout: 100,
		out: categoryHoverOut
	};
	
	var dropdownConfig ={
		over: dropdownHoverIn,
		timeout: 100,
		out: dropdownHoverOut
	};	
	
	$(".inactive_category").hoverIntent(categoryConfig);
	
	$(".dropdown_trigger").hoverIntent(dropdownConfig);










	$("#search_button").show();
	
	// default text
	$(".searchbox").focus(function(srcc)
	{
		if ($(this).val() == $(this)[0].title)
		{
			$(this).removeClass("defaultTextActive");
			$(this).val("");
		}
	});
	
	$(".searchbox").blur(function()
	{
		if ($(this).val() == "")
		{
			$(this).addClass("defaultTextActive");
			$(this).val($(this)[0].title);
		}
	});
	
	$(".searchbox").blur();
	
	$("#search_form").submit(function() {
		$(".searchbox").each(function() {
			if($(this).val() == this.title) {
				$(this).val("");
			}
		});
	});
	// end default text
	
	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
			
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});
			
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}


	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 500, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	$("ul#topnav li .sub").css({'opacity':'0'});
	$("ul#topnav li").hoverIntent(config);
	
	
	
	$(".tooltip[title]").tooltip({		 
		tip: '#info_tooltip',
		position: 'bottom right',
		offset: [10, 0]
	}); 
	
	$("#recommended_infotip_trigger").tooltip({		 
		tip: '#recommended_infotip',
		position: 'bottom right',
		offset: [-15, -852]
	}); 
	
	$(".tagbak_tip_trigger").tooltip({		 
		tip: '#tagbak_tip',
		position: 'bottom center',
		offset: [10, 0]
	}); 	
	
	$(".special_price").tooltip({		 
		tip: '#price_applies_tip',
		position: 'bottom right',
		offset: [10, -10]
	}); 
	
	$("#mopay_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#mopay_recommended_box',
		offset: [-13, -14],
		delay: 50
	});
	
	$("#phone-recycle-bank_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#phone-recycle-bank_recommended_box',
		offset: [-13, -14],
		delay: 50
	});
	
	$("#money-4-my-mobile_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#money-4-my-mobile_recommended_box',
		offset: [-13, -14],
		delay: 50
	});
	
	$("#rpc-recycle_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#rpc-recycle_recommended_box',
		offset: [-13, -14],
		delay: 50
	});
	
	$("#mobile-phone-xchange_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#mobile-phone-xchange_recommended_box',
		offset: [-13, -14],
		delay: 50
	});

	$("#cash-4-phones_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#cash-4-phones_recommended_box',
		offset: [-13, -14],
		delay: 50
	});
	
	$("#royal-mail-simply-drop_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#royal-mail-simply-drop_recommended_box',
		offset: [-13, -14],
		delay: 50
	});
	
	$("#protect-your-bubble_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#protect-your-bubble_recommended_box',
		offset: [-13, -14],
		delay: 50
	});
	
	$("#gadget-cover_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#gadget-cover_recommended_box',
		offset: [-13, -14],
		delay: 50
	});	
	
	$("#bozowi_dropdown_trigger").tooltip({
		position: 'bottom right', 
		tip: '#bozowi_recommended_box',
		offset: [-13, -14],
		delay: 50
	});	
		
	
	$("#search_button_submit").click(function() {
		$("#search_form").submit();
		return false;
	});
					   
	$("#autoComplete").autocomplete("/search/",
	{
		autoFill: false,
		minChars: 1,
		max: 30,
		delay: 300,
		width: 410,
		scrollHeight: 350,
		selectFirst: false,
		//cacheLength: 100,
		matchContains: true,
		matchSubset: false,
		formatItem: formatItem,
		formatMatch: formatMatch,
		formatResult: formatResult
		//mustMatch: true,
	 }).result(function(event, row){
		if(row[0] != "c") {
			location.href = row[2];
		}
	});

	//
	// Continue Prompt Stuff
	//
	$("a.continue_prompt").click(function(){
		$.fancybox({ 
			'width'				: 500,
			'height'			: 250,
			'autoScale'			: false,
			'type'				: 'iframe',
			'href'				: $(this).attr("href") + '&iframe=true'
		});
		return false;
	});

	$("#low_rating_container a.close").click(function() {
		parent.$.fancybox.close();
		return false;
	});
	
	//
	// Why compare box
	//
	$("a.why_compare").click(function(){
		$.fancybox({ 
			'width'				: 620,
			'height'			: 550,
			'autoScale'			: false,
			'type'				: 'iframe',
			'href'				: $(this).attr("href") + '?iframe=true'
		});
		return false;
	});
	
	//
	// Iframe Close
	//
	$("#iframe_container a.close").click(function() {
		parent.$.fancybox.close();
		return false;
	});
	
	$("#outclick_fancybox a.close").click(function() {
		$.fancybox.close();
	});
	
	
	// Gold video
	$("a#gold_video").fancybox();

	// Music Magpie video
	$("a#mm_ad").fancybox();
	
	// Gadget Show Videos
	$("a#seen_on_gadget_show").fancybox();

	$("a#watch_gadget_show_video").fancybox();

	// Newsletter
	$("a#newsletter-signup").click(function(){
		$.fancybox({ 
			'width'				: 279,
			'height'			: 250,
			'autoScale'			: false,
			'type'				: 'iframe',
			'href'				: $(this).attr("href") + '?iframe=true'
		});
		return false;
	});
	
	
	//
	// Exit message
	//	
	/*if(typeof parent.outclick_fancybox_done == 'undefined') {
		parent.outclick_fancybox_done = false;
	}
	$("a.outclick_fancybox_click").click(function(){
		if(parent.outclick_fancybox_done == false || outclick_fancybox_done == false) {
			parent.$.fancybox.close();			
			parent.$("#content_box").animate({"height": "show"}, { duration: 1000 });
			parent.$('.message_show').hide();
			parent.$('.message_hide').show();
		}
		else {
			parent.$.fancybox.close();
		}
		parent.outclick_fancybox_done = true;
	});
	*/
	
	if(typeof outclick_fancybox_done == 'undefined') {
		outclick_fancybox_done = false;
	}
	$("a.outclick_fancybox_click").click(function(){
		if(parent.outclick_fancybox_done == false) {
			parent.$.fancybox.close();			
			parent.$("#content_box").animate({"height": "show"}, { duration: 1000 });
			parent.$('.message_show').hide();
			parent.$('.message_hide').show();
		}
		else {
			parent.$.fancybox.close();
		}
		parent.outclick_fancybox_done = true;
	});
	
	
	// Exit Message (hidden div method)
	$('a#outclick_fancybox_click').fancybox({
		//'hideOnContentClick': true,
		//'speedIn'		:	200, 
		//'speedOut'	:	200, 
		//'overlayShow'	:	false,	
		'scrolling'		: 	'no',
		'titleShow'		: 	false,        		
		'autoDimensions': 	false,
		'width'         : 	750,
		'height'        : 	'auto'
	});

	// Newsletter Form
	 var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){}  };
  var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
  options = { url: 'http://compareandrecycle.us2.list-manage.com/subscribe/post-json?u=629fa0cad4f48c4dec53c5447&id=d63f4572d1&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
                beforeSubmit: function(){
                    $('#mce_tmp_error_msg').remove();
                    $('.datefield','#mc_embed_signup').each(
                        function(){
                            var txt = 'filled';
                            var fields = new Array();
                            var i = 0;
                            $(':text', this).each(
                                function(){
                                    fields[i] = this;
                                    i++;
                                });
                            $(':hidden', this).each(
                                function(){
                                	if ( fields[0].value=='MM' && fields[1].value=='DD' && fields[2].value=='YYYY' ){
                                		this.value = '';
									} else if ( fields[0].value=='' && fields[1].value=='' && fields[2].value=='' ){
                                		this.value = '';
									} else {
	                                    this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
	                                }
                                });
                        });
                    return mce_validator.form();
                }, 
                success: mce_success_cb
            };
  $('#mc-embedded-subscribe-form').ajaxForm(options);
	


	// end document ready
});


function formatItem(row) {
	var formatted = "";
	if(row[0] == "p") {
		// products or suggested products
		formatted = "<span class='ac_product'><span class='ac_image'><img src='"+row[3]+"' align='middle' class='product_image_64x64' /></span><span class='ac_text'>"+row[1]+"</span></span>";
	}
	else if(row[0] == "m") {
		// manufacturers
		formatted = "<span class='ac_manufacturer'>List all <span class='ac_match_word'>"+row[1]+"</span> products</span>";
	}
	else if(row[0] == "s") {
		// suggestion comment
		formatted = "<span class='ac_suggest'>"+row[1]+"</span>";
	}
	else {
		// comments
		formatted = "<span class='ac_comment'>"+row[1]+"</span>";
	}
	return formatted;
}

function formatMatch(row) {
	if(row[0] == "c") {
		return [""];
	}
	else {
		return row[1];
	}
}

function formatResult(row) {
	if(row[0] == "c") {
		return [""];
	}
	else {
		return row[1];	
	}
}

// Price Comparison
$("#price_comparison tr.off").mouseover(function() {
	$(this).addClass("over");
});

$("#price_comparison tr.off").mouseout(function() {
	$(this).removeClass("over");
});


$("#gold_comparison_intro_expand").click(function() {
	$("#gold_comparison_intro_text").toggle('slow');
	return false;
});

$("#gold_comparison_intro2_expand").click(function() {
	$("#gold_comparison_intro2_text").toggle('slow');
	return false;
});

function ShowStripShow(){
	$("#content_box").animate({"height": "show"}, { duration: 1000 });
	$('.message_show').hide();
	$('.message_hide').show();
}
	
function ShowStripHide(){
	$("#content_box").animate({"height": "hide"}, { duration: 1000 });
	$('.message_hide').hide();
	$('.message_show').show();
}

var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';var err_style = '';
try{
    err_style = mc_custom_error_style;
} catch(e){
    err_style = 'margin: 1em 0 0 0; padding: 1em 0.5em 0.5em 0.5em; background: FFEEEE none repeat scroll 0% 0%; font-weight: bold; float: left; z-index: 1; width: 80%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: FF0000;';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
  style.styleSheet.cssText = '.mce_inline_error {' + err_style + '}';
} else {
  style.appendChild(document.createTextNode('.mce_inline_error {' + err_style + '}'));
}
head.appendChild(style);

function mce_success_cb(resp){
    $('#mce-success-response').hide();
    $('#mce-error-response').hide();
    if (resp.result=="success"){
        $('#mce-'+resp.result+'-response').show();
        $('#mce-'+resp.result+'-response').html(resp.msg);
        $('#mc-embedded-subscribe-form').each(function(){
            this.reset();
    	});
    } else {
        var index = -1;
        var msg;
        try {
            var parts = resp.msg.split(' - ',2);
            if (parts[1]==undefined){
                msg = resp.msg;
            } else {
                i = parseInt(parts[0]);
                if (i.toString() == parts[0]){
                    index = parts[0];
                    msg = parts[1];
                } else {
                    index = -1;
                    msg = resp.msg;
                }
            }
        } catch(e){
            index = -1;
            msg = resp.msg;
        }
        try{
            if (index== -1){
                $('#mce-'+resp.result+'-response').show();
                $('#mce-'+resp.result+'-response').html(msg);            
            } else {
                err_id = 'mce_tmp_error_msg';
                html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
                
                var input_id = '#mc_embed_signup';
                var f = $(input_id);
                if (ftypes[index]=='address'){
                    input_id = '#mce-'+fnames[index]+'-addr1';
                    f = $(input_id).parent().parent().get(0);
                } else if (ftypes[index]=='date'){
                    input_id = '#mce-'+fnames[index]+'-month';
                    f = $(input_id).parent().parent().get(0);
                } else {
                    input_id = '#mce-'+fnames[index];
                    f = $().parent(input_id).get(0);
                }
                if (f){
                    $(f).append(html);
                    $(input_id).focus();
                } else {
                    $('#mce-'+resp.result+'-response').show();
                    $('#mce-'+resp.result+'-response').html(msg);
                }
            }
        } catch(e){
            $('#mce-'+resp.result+'-response').show();
            $('#mce-'+resp.result+'-response').html(msg);
        }
    }
}
