SET_DEBUG_LEVEL=false, SET_DEBUG_COUNT=0;
function DEBUG_LEVEL(level) { var t = level||false; window.SET_DEBUG_LEVEL=(t==1?true:t); if(window.SET_DEBUG_LEVEL==true){ debug("DEBUG is activated.",'warn',1); } }
function debug(m,e,dl){
	var message=m||'', error=e||'log'; dl = dl||false;
	if(typeof error=="string") { error = trim(error.toLowerCase()); } else if(error==true || error==1) { dl = true; }
	if(SET_DEBUG_LEVEL && SET_DEBUG_LEVEL==true || SET_DEBUG_LEVEL>0 || dl==true || dl>0) {
		switch(error) {
			case "error":
				window.console && window.console.error ? console.error(message) : null;
				break;
			case "warn":
				window.console && window.console.warn ? console.warn(message) : null;
				break;
			case "info":
				window.console && window.console.info ? console.info(message) : null;
				break;
			case "log":
				window.console && window.console.log ? console.log(message) : null;
				break;
			default:
				window.console && window.console.debug ? console.debug(message) : null;
		}
		SET_DEBUG_COUNT++;
	}
	else {
		if(SET_DEBUG_COUNT==0) {
			//window.console && window.console.warn ? console.warn("DEBUG is being called. Set DEBUG_LEVEL() to see debug messages!") : null;
			SET_DEBUG_COUNT++;
		}
	}
};

PRIMORDIAL_LOADED = false;
var JC_Bootloader = {
	connection:true, is_ready:false, debug:false, css_list:[], js_list:[], job_list:[], running:[], is_callback_called:false,
	init: function(debug){
		this.load_all_css();
		this.load_all_js();
		this.run_all_jobs();

		window.PRIMORDIAL_LOADED = true;
		this.is_ready = true;
	},
	ready: function(callback){
		var callback = callback || function(){};
		this.init();
		if(this.is_ready==true && typeof callback=="function"){ callback(); this.is_callback_called=true; }
		window.debug && this.is_ready==true ? debug("JC Bootloader is "+(this.is_ready?'Ready':'Not Ready.'),(this.is_ready?'log':'warn'),1) : null;
		return true;
	},
	css: function(s) {
		var new_css = s.toString()||'', c=0;
		new_css = new_css.split(',');
		for(i in new_css) {
			new_css[i] = trim(new_css[i]);
			if($.inArray(new_css[i],this.css_list)==-1) {
				this.css_list.push(new_css[i]);
				this.debug && window.debug ? debug("Added external style: "+new_css[i]) : null;
			}
		}
	},
	load_css: function(s) {
		this.css(s);
		this.load_all_css();
	},
	load_all_css: function() {
		var c=0;
		var existing_css = $("link").map(function(){ return $(this).attr('href').replace('/css/',''); });
		var already_loaded = [];
		for(x in this.css_list) {
			if($.inArray(trim(this.css_list[x]),existing_css)==-1) {
				var file = trim(this.css_list[x]);
				var fullpath = (!file.match(/^http:\/\//) && !file.match(/^\/css\//) ? "/css/"+file : file);
				$("HEAD").append("<link type=\"text/css\" href=\""+fullpath+"\" rel=\"stylesheet\" />");
				c++;
				delete this.css_list[x];
			}
			else { already_loaded.push(this.css_list[x]); delete this.css_list[x]; }
		}
		if(c>0){ this.debug && window.debug ? debug("Loaded external ("+c+") styles: "+this.css_list.join(',')) : null; }
		else if(c==0 && already_loaded.length>0){ this.debug && window.debug ? debug("Already loaded ("+already_loaded.length+") styles: "+already_loaded.join(', ')) : null; }
		else{ this.debug && window.debug ? debug("No external styles loaded.",this.debug) : null; }
	},
	js: function(j) {
		var new_js = j.toString()||'', c=0;
		new_js = new_js.split(',');
		for(i in new_js) {
			new_js[i] = trim(new_js[i]);
			if($.inArray(new_js[i],this.js_list)==-1) {
				this.js_list.push(new_js[i]);
				this.debug && window.debug ? debug("Added external script: "+new_js[i],this.debug) : null;
			}
		}
	},
	load_js: function(s) {
		this.js(s);
		this.load_all_js();
	},
	load_all_js: function() {
		var c=0;
		var existing_js = $("script").map(function(){ var s=$(this).attr('src')||false; s=(s!=false?s.replace('/js/',''):s); return s; });
		var already_loaded = [];
		for(x in this.js_list) {
			if($.inArray(trim(this.js_list[x]),existing_js)==-1) {
				var file = trim(this.js_list[x]);
				var fullpath = (!file.match(/^http:\/\//) && !file.match(/^\/js\//) ? "/js/"+file : file); //.replace(/^http:\/\//gi,"/extjs/"));
				var script = document.createElement('script');
				script.type = 'text/javascript';
				script.src = fullpath;
				$("BODY", document).append(script);
				c++;

				delete this.js_list[x];
			}
			else { already_loaded.push(this.js_list[x]); delete this.js_list[x]; }
		}
		if(c>0){ this.debug && window.debug ? debug("Loaded external ("+c+") scripts: "+this.js_list.join(', ')) : null; }
		else if(c==0 && already_loaded.length>0){ this.debug && window.debug ? debug("Already loaded ("+already_loaded.length+") scripts: "+already_loaded.join(', ')) : null; }
		else{ this.debug && window.debug ? debug("No external scripts loaded.") : null; }
	},
	job: function(name,duration,task) {
		var j = { name:name.toString()||null, duration:parseInt(duration)||0, task:task||null, active:false, lastchanged:null };
		if(j.name!=null && j.duration>0 && typeof j.task=="function") {
			var job_exist=false, index=0, job_list=this.job_list;
			for(x in job_list) {
				if(j.name==job_list[x].name) { job_exist=true; break; } else { index++; }
			}
			if(job_exist==true) {
				job_list[index].task = j.task;
				job_list[index].duration = j.duration;
				this.debug && window.debug ? debug("Updated job ("+job_list[index].name+") on running every "+job_list[index].duration+" secs.") : null;
			}
			else {
				j.active = false;
				job_list.push(j);
				//this.debug && window.debug ? debug("Added job ("+j.name+") to run every "+j.duration+" secs.") : null;
			}
		}
		else { this.debug && window.debug ? debug("Invalid job args.") : null; }
	},
	remove_job: function(n) {
		var name = n.toString() || '';
		if(this.job_list.length>0) {
			var c=null, index=null;
			name = trim(name);
			var c=0;
			for(x in this.job_list) {
				if(this.job_list[x].name==name) {
					this.stop_job_name(name);
					for(y in this.running) {
						if(this.running[y].name==this.job_list[x].name) {
							delete this.running[y];
						}
					}
					delete this.job_list[x];
					c++;
					break;
				}
			}
			if(c>0) { this.debug && window.debug ? debug("Removed job: "+name) : null; }
			else { this.debug && window.debug ? debug("Cound not find and remove job: "+name) : null; }
		}
		else { debug("No jobs are currently running."); }
	},
	run_all_jobs: function(one){
		if(this.job_list.length>0) {
			for(x in this.job_list) {
				if(this.job_list[x].active==false && typeof this.job_list[x].task=="function") {
					this.job_list[x].active = true;
					var D=(new Date());
					var start_time=D.getHours()+":"+D.getMinutes()+":"+D.getSeconds();
					D.setSeconds(D.getSeconds()+this.job_list[x].duration);
					var next_time=D.getHours()+":"+D.getMinutes()+":"+D.getSeconds();
					this.debug && window.debug ? debug("Running job ("+this.job_list[x].name+") every "+(this.job_list[x].duration)+" secs"+(this.jobs[x].duration>=60?" ("+(this.job_list[x].duration/60)+" mins)":"")+". [started: "+start_time+" > next: "+next_time+"]") : null;
					this.run_job_id(x);
				}
			}
		}
		else { this.debug && window.debug ? debug("No jobs to run.") : null; }
	},
	run_job_id: function(i){
		var index = i||-1;
		if(index>-1 && this.job_list.length>0 && this.job_list[index] && typeof this.job_list[index].task=="function") {
			var bt_j = this;
			for(x in this.running) {
				if(this.running[x].name==bt_j.job_list[index].name) {
					clearInterval(this.running[x].id);
					break;
				}
			}
			var _time_ = bt_j.job_list[index].duration*1000;
			var _func_ = function(){ bt_j.job_list[index].task.call(); };
			var int_id = setInterval(_func_, _time_);
			bt_j.job_list[index].active = true;
			this.running.push({ id:int_id, index:index, name:bt_j.job_list[index].name, lastchanged:bt_j.job_list[index].lastchanged||null });
			create_cookie("JOB:"+bt_j.job_list[index].name, "CN"); // CY=ChangedYes|CN=ChangedNo
		}
		else { this.debug && window.debug ? debug("Could not find job index ("+index+")") : null; }
	},
	run_job_name: function(n){
		var name = n.toString() || null;
		if(this.job_list.length>0) {
			var index = -1;
			for(x in this.job_list) {
				if(this.job_list[x].name==name) { index = x; break; }
			}
			if(index>-1 && typeof this.job_list[index].task=="function") {
				this.run_job_id(index);
				var queue = 0;
				for(x in this.running) {
					if(this.running[x].name==this.job_list[index].name) {
						queue++;
						break;
					}
				}
				this.debug && window.debug ? debug((queue>0?"Restarting":"Starting")+" job: "+this.job_list[index].name) : null;
			}
			else { this.debug && window.debug ? debug("Could not find job: "+name) : null; }
		}
		else { this.debug && window.debug ? debug("No jobs exist yet.") : null; }
	},
	stop_job_name: function(n){
		var name = n.toString() || '';
		if(this.running.length>0) {
			var c=null, index=null;
			name = trim(name);
			for(x in this.running) {
				if(this.running[x].name==name) {
					c=this.running[x].id;
					index=this.running[x].index;
					break;
				}
			}
			if(c!=null) {
				clearInterval(c);
				this.job_list[index].active = false;
				this.debug && window.debug ? debug("Stopped running job: "+name) : null;
			}
			else {
				this.debug && window.debug ? debug("Cound not find and stop running job: "+name) : null;
			}
		}
		else { this.debug && window.debug ? debug("No jobs are currently running.") : null; }
	},
	stop_all_jobs: function(){
		if(this.running.length>0) {
			for(x in this.running) {
				clearInterval(this.running[x].id);
				this.job_list[this.running[x].index].active = false;
			}
			this.running = [];
			this.debug && window.debug ? debug("Stopped all running jobs.") : null;
		}
		else { this.debug && window.debug ? debug("No jobs are currently running.") : null; }
	}
}

var Drawer = {
	debug:false, is_ready:false, current: null,
	init_config: {
		width: 415,
		height: $(document).height(),
		height_extended: 5
	},
	init: function() {
		var HideLayer = function(){ if($("#drawer_outer_wrap .drawer:visible").length>0){ Drawer.hide(); } };
	    	$(window).bind('keyup resize',function(e){
			Drawer.reconfig(true);
			if(e.type=='keyup' && e.keyCode==27) { HideLayer(); } // close drawer via ESC key.
	    	});
		$(document).bind('click',function(e){
			if(!$(e.target).closest("#drawer_outer_wrap,#compare_btn_cont").length) { HideLayer(); }
		});
		$("input.tbLarge").focus(HideLayer);
		$("#drawer_outer_wrap .drawerClose").click(HideLayer);

		$("#navBar a.drawer_btn").click(function(){
			// close drawer ELSE display another selected drawer...
			if(Drawer.current==this.id && $(this).hasClass('active')) { Drawer.hide(this.id); }
			else { Drawer.view(this.id); }
			return false;
		});

		$("a.drawer_open").live("click",function(){
			var rel = $(this).attr('rel');
			if(rel!='') { Drawer.view(trim(rel)); }
			return false;
		});

		this.is_ready = true;
		this.debug ? debug("Drawer initializing...",this.debug) : null;
		return true;
	},
	debug: function() {
		this.debug = true;
		return this;
	},
	ready: function(callback) {
		var _status = "Drawer is ";
		var callback = callback || null;
		this.init();
		if(this.is_ready==true) {
			_status += "Ready";
			if(typeof callback=="function") { callback(); _status += " and callback called."; }
		}
		else {
			_status += "NOT Ready";
		}
		this.debug ? debug(_status,this.debug) : null;
		return this.is_ready;
	},
	hide: function(d) {
		var drawer = d || 'all';
		this.current = null;
		drawer = (drawer!='all' ? "#drawer_"+drawer : ".drawer");
		$(drawer+":visible").fadeOut(500);
		$("a.drawer_btn").removeClass("active");
		$("#drawer_inner_wrap").find("#drawer_inner_content").fadeOut().parent().animate({width:0}, {duration:500, easing:'easeInBack'});
		this.debug ? debug("Drawer hiding > "+drawer,this.debug) : null;
		// hide the comparison counter if not the comparison drawer to view.
		window.ComparisonTracker && ComparisonTracker.contract().inactive();
	},
	view: function(d) {
		d = d.toLowerCase();
		var last_config = { height:0, width:0 };

		// initialize configurations per drawer.
		this.init_config.height = $(document).height()-$("#header").height()+this.init_config.height_extended;

		var set_drawer_width = this.init_config.width;
		if(this.config[d]) {
			set_drawer_width = this.config[d]['width'] || set_drawer_width;
		}

		// set the current (document) drawer height..
		$("#drawer_outer_wrap").css("height",this.init_config.height);

		// open drawer
		if(this.current==null) {
			$("#drawer_inner_wrap").animate({width:"+="+set_drawer_width+"px"}, {duration:500, easing:'easeOutBack'}).find("#drawer_inner_content").fadeIn();
		}
		else {
			Drawer.style_it({width:set_drawer_width});
		}

		// set new current drawer.
		this.current = d || null;
		var display_drawer = "#drawer_"+this.current;
		$(".drawer:visible:not("+display_drawer+")").hide();
		$(display_drawer).fadeIn();
		$("a.drawer_btn").removeClass("active");
		$("a.drawer_btn#"+this.current).toggleClass("active");

		// hide the comparison counter if not the comparison drawer to view.
		if(this.current!="comparison" && window.ComparisonTracker){
			ComparisonTracker.contract().inactive();
		}

		// apply callbacks...
		if(this.callbacks[d]) {
			Drawer.callbacks[d].call();
			this.debug ? debug("Drawer viewing > "+d,this.debug) : null;
		}
		else {
			debug("Drawer view ("+d+") not found.",'error',1);
		}
	},
	style_it : function(opt) {
		var opt = opt || {width:this.init_config.width, height:this.init_config.height};
		var options = {width:(opt.width||this.init_config.width)+'px', height:(opt.height||this.init_config.height)+'px'};
		$("#drawer_inner_wrap").animate(options);
		this.debug ? debug("Drawer styling it (w="+options.width+" | h="+options.height+")",this.debug) : null;
		return true;
	},
	reconfig: function(bool){
		this.init_config.height = $(document).height()-$("#header").height()+this.init_config.height_extended;
		if(bool) {
			$("#drawer_inner_wrap").css('height',this.init_config.height);
			this.debug ? debug("Drawer reconfiguring height to ("+this.init_config.height+")",this.debug) : null;
		}
	},
	config: {
		default_width:415,
		settings:{width:440},
		register:{width:500},
		budget:{width:377},
		comparison:{width:415}
	},
	callbacks: {
		register: function() {
			// Login form
			$("#drawer_register #logIn").submit(function(){
				var e = [];
				var data = {email:$("#drawer_register #logIn input[name='email']").val(), password:$("#drawer_register #logIn input[name='password']").val()};

				if(data.email=='' || data.email=='Email' || (data.email!='' && validate_email(data.email)==false)) {
					e.push("Email is incorrect or invalid.");
				}
				if(data.password=='') {
					e.push("Password is required.");
				}
				if(e.length==0) {
					$.ajax({async:false, dataType:"json", type:"POST", url:"/ajax/feature?f=login", data:data,
						success: function(json) {
							if(json.error==null) {
								if(window.location.href.match(/search[?]/)) {
									uri = replace_query_var("ref","ls",window.location.href.split('#')[0],true)+(window.location.href.split('#')[1]!=undefined?"#"+window.location.href.split('#')[1]:'');
								}
								else {
									uri = replace_query_var("ref","lj",(!window.location.href.match(/\.com\/[?]/gi)?window.location.href+"?":""),true);
								}
								window.location.href = uri;
							}
							else {
								$("#drawer_register #drawerLoginStatus").html("<div id='registration_error'>"+json.payload+"</div>").show();
							}
						},
						error: function(html){
							alert("Oops ... Something happened.\n\nThe team has been notified.");
						}
					});
			    }
			    else {
			    	$("#drawer_register #drawerLoginStatus").html("<div id='registration_error'>"+e.join("<br />")+"</div>").show();
			    }
				return false;
			});
			$("#drawer_register #logIn #btnLogin").live("click",function(){
				$("#drawer_register #logIn").trigger("submit");
				return false;
			});

			// Register form.
			$("#drawer_register #register_btn").live("click",function(){
				var e = [];
				var data = {email:$("#drawer_register #email").val(), password1:$("#drawer_register #password1").val(), password2:$("#drawer_register #password2").val()};

				if(data.email=='' || data.email=='Email' || (data.email!='' && validate_email(data.email)==false)) {
					e.push("Email is incorrect or invalid.");
				}
				if(data.password1=='' || data.password2=='') {
					e.push("Password is required.");
				}

			    if(data.password2=='') {
				    e.push("Retype Password is required.");
			    }
			    if(data.password1!='' && data.password2!='' && data.password1!=data.password2) {
				    e.push("Both Passwords must match.");
			    }
			    if(data.password1!='' && data.password2!='' && (data.password1.length<6 || data.password2.length<6)) {
				    e.push("Password must be more 6 characters or more.");
			    }

			    if(e.length==0) {
				    $.ajax({async:false, dataType:"json", url:"/ajax/feature?f=register&action=add", type:"POST", data:data,
					    success: function(json) {
				    		if(json.error==null) {
							//$("#drawer_register #drawerRegistrationStatus").html(json.payload).show();
							uri = replace_query_var("ref","welcome",window.location.href);
							LOCATOR.go(uri);
				    		}
				    		else {
							$("#drawer_register #drawerRegistrationStatus").html(json.payload).show();
				    		}
					    },
					    error: function(html){
						    $("#drawer_register #drawerRegistrationStatus").html("<div id='registration_error'>Oops ... Something went very, very wrong and I could not register you.\n\n I've notified the Guys!</div>").show();
					    }
				    });
			    }
			    else {
			    	$("#drawer_register #drawerRegistrationStatus").html("<div id='registration_error'>"+e.join("<br />")+"</div>").show();
			    }
				Drawer.reconfig(true);

				return false;
			});

		},
		settings: function() {
			// Disable/Enable Mini-Tabs
			var settings = $("#drawer_settings");
			$(".drawer_mini_tab:visible", settings).hide();
			$("#display_settingInfo", settings).show();

			$(".drawerTabs a", settings).live("click",function(){
				var id = this.id;
				section = $("#drawer_settings #display_"+id);
				$(".drawer_mini_tab:visible", settings).hide();
				$(".drawerTabs a.active", settings).removeClass("active");
				$(this).addClass("active");
				$(".ajax_result", section).remove();
				$("form", section).show();
				$(".change_status", settings).empty().hide();
				section.show();
			});

			// re-enable the last active minitab
			if($(".drawerTabs a.active", settings).length) {
				$(".drawerTabs a.active", settings).click();
			}

			var INFO = $("#display_settingInfo", settings);
			var PREF = $("#display_settingPref", settings);
			var EMAIL = $("#display_settingEmail", settings);
			var PASS = $("#display_settingPass", settings);

			$("form input:password", EMAIL).val('');

			if($("#display_settingInfo", settings).hasClass('just_warn')) {
				// just show settings message if not logged in yet...
				$("#display_settingInfo.just_warn", settings).show();
				return false;
			}

			// get user settings (info, pref, email, pass)
		    $.ajax({async:false, dataType:"json", url:"/ajax/feature?f=settings&action=get-settings",
		    	success:function(json){ window.PAYLOAD = json; },
				error:function(json){ alert("Error: Could not get your settings info. Please Try again"); }
		    });

		    if(PAYLOAD.error==null && PAYLOAD.payload.info && PAYLOAD.payload.pref && PAYLOAD.payload.email && PAYLOAD.payload.pass) {
				INFO.html(window.PAYLOAD.payload.info);
				PREF.html(window.PAYLOAD.payload.pref);
				EMAIL.html(window.PAYLOAD.payload.email);
				PASS.html(window.PAYLOAD.payload.pass);

				// Form - change info
				$("#save_settings", INFO).live("click",function(){
					$.ajax({async:false, dataType:"json", url:"/ajax/feature?f=settings", type:"POST", data:$("form",INFO).serialize(),
						success: function(html) {
							PAYLOAD = html;
							var result = PAYLOAD.payload;
							if(result.status=="saved") {
								$(".ajax_result", INFO).remove();
								$("form",INFO).hide();
								INFO.append("<div class='ajax_result'><br><br><a id='edit_settings_my_info' href='javascript:void(0)'>Return to My Info</a></div>");
								$("#edit_settings_my_info", INFO).click(function(){
									$(".change_status", INFO).empty().hide();
									$(".ajax_result",INFO).remove();
									$("form",INFO).show();
									return false;
								});
							}
							$(".change_status", INFO).html(result.message).show();
						},
						error: function(html){
							alert("Oops ... Something happened.\n\nYour settings were not saved. The team was notified.");
						}
					});
					return false;
				});

				// Form - change pref
				$("#save_settings", PREF).live("click",function(){
					$.ajax({async:false, dataType:"json", url:"/ajax/feature?f=settings", type:"POST", data:$("form",PREF).serialize(),
						success: function(html) {
							PAYLOAD = html;
							var result = PAYLOAD.payload;
							if(result.status=="saved") {
								$(".ajax_result", PREF).remove();
								$("form", PREF).hide();
								PREF.append("<div class='ajax_result'><br><br><a id='edit_settings_my_pref' href='javascript:void(0)'>Return to My Preferences</a></div>");
								$("#edit_settings_my_pref", PREF).click(function(){
									$(".change_status", PREF).empty().hide();
									$(".ajax_result", PREF).remove();
									$("form", PREF).show();
									return false;
								});
							}
							$(".change_status", PREF).html(result.message).show();
						},
						error: function(html){
							alert("Oops ... Something happened and I could not save your settings.\n\nThe website alien master has been notified.");
						}
					});
					return false;
				});

				// Form - change email
				$("#save_settings", EMAIL).live("click",function(){
					//$(".cancel_settings", EMAIL).click(close_settings_drawer);
					$status = $(".change_status", EMAIL);
					$status.empty();

					$form = $("form", EMAIL);
					email = $("#email", $form).val();
					password = $("#password", $form).val();

					var e = [];
					if(email=='') { e.push("- Email address is required"); }
					if(email!='' && validate_email(email)==false) { e.push("- Email address must be valid."); }
					if(password=='') { e.push("- Current Password is required"); }

					if(e.length==0) {
						$.ajax({async:false, dataType:"json", url:"/ajax/feature?feature=settings&action=change-email", type:"POST", data:$form.serialize(),
							success: function(json) {
								if(json.error==null && json.payload.message) {
									$status.empty().html(json.payload.message).show();
									if(json.payload.profile && json.payload.profile.email) {
										$("#current_email", $form).text(json.payload.profile.email);
										$("#email", $form).val('');
										$("#password", $form).val('');
									}
								}
								else {
									$status.empty().html(json.payload).show();
								}
							},
							error: function(html){
								$status.empty().html("Oops ... Something happened.<br><br>Cannot change your email at the momemt. The team was notified.").show();
							}
						});
					}
					else {
						$status.empty().html(e.join("<br>")).show();
					}
					return false;
				});

				// Form - change password
				$("#save_settings", PASS).live("click",function(){
					form = $("form", PASS);
					var p = {old:$("#passwd_old", EMAIL).val(), new1:$("#passwd_new1", EMAIL).val(), new2:$("#passwd_new2", EMAIL).val()};
					if(p.old!='' && p.new1!='' && p.new2!='' && p.new1==p.new2) {
						$.ajax({url:"/ajax/feature?feature=us&action=save", type:"POST", data:$("form", EMAIL).serialize(),
							success: function(html) {
								$("form input:password", EMAIL).val('');
								$("form input:password + span", EMAIL).text('');
								$(".change_status", EMAIL).empty().html(html).show();
								$(".cancel_settings", EMAIL).click(close_settings_drawer);
							},
							error: function(html){
								alert("Oops ... Something happened.\n\nYour settings were not saved. The team was notified.");
							}
						});
					}
					else {
						$("#passwd_old + span").html((p.old==''?"&laquo; Required!":""));
						if(p.new1!=''&&p.new2!='') {
							$("#passwd_new2 + span").html((p.new1!=''&&p.new2!=''&&p.new1!=p.new2?"New Password/Confirm Password must match":""));
						}
						else {
							$("#passwd_new1 + span").html((p.new1==''?"&laquo; Required":""));
							$("#passwd_new2 + span").html((p.new2==''?"&laquo; Required":""));
						}
					}
					return false;
				});
			}
			else {
				alert("Oops ... Unable to get Setttings.");
			}

		},
		budget: function(){
			var budget = $("#drawer_budget");
			$('input.headerButton').click(function() {
				var budget_amount = parseFloat($("#budget_amount").val());
				var data = {pref:"budget", amount:budget_amount};
				$.ajax({url:"/ajax/feature?feature=us&action=save", type:"POST", data:data,
					success: function(html) {
						$("#show_budget_amount span:first").text("$"+budget_amount+" -");
						$('#setBudget').hide("slide", { direction: "left" }, "slow");
					},
					error: function(html){
						alert("Oops ... Something happened and I could not save budget amount.\n\nThe website alien master has been notified.");
					}
				});
			});
			$(".drawerTabs a", budget).live("click",function() {
				var id = this.id;
				$(".drawer_mini_tab:visible:not(#display_"+id+")", budget).hide();
				$(".drawerTabs a", budget).removeClass("active");
				$(this).addClass("active");
				$("#display_"+id+".drawer_mini_tab", budget).show();

				if(id=="budgetDash") {
					$("#setBudget", budget).show("slide", { direction: "left" }, "slow");
				}
			});
			$("#display_budgetDash.drawer_mini_tab", budget).show();
		},
		alerts: function(){
		    $.ajax({async:false, dataType:"json", url:"/ajax/feature?f=alerts&action=get-items",
		    	success:function(msg){ PAYLOAD = msg; },
				error:function(msg){ alert("Error: Could not find your Alerts. Try again"); }
		    });
		    if(PAYLOAD.error==null) {
				var alert_minitext = $("#drawer_alerts #alerts_minitext");
		    	var data = "";
		    	var get_items = {total:0, items:[]};
		    	get_items = PAYLOAD.payload || get_items;
		    	if(get_items.total>0) {
					for(var i=0; i<get_items.total; i++) {
						var item = get_items.items[i];
				    	data += "<div class='drawer_item_container "+(item.watching_met==true?"alert_meets_price":"")+"'>";
				    	data += "	<div class='drawer_item_head'>";
				    	data += "		<a class='drawer-alert-remove-item' href='/ajax/feature?f=alerts&action=remove&wid="+item.id+"'></a>";
				    	data += "		<div class='for_display'>";
				    	data += "			<h2><a href='/details?"+item.product_key+"'>"+abbrev(item.title,85,true)+"</a></h2>";
				    	data += "			<div class='drawer_price_cont'><span>$"+format_number(item.current_price)+"</span><em>current price</em></div>";
				    	data += "		</div>";
				    	data += "	</div>";
				    	data += "	<div class='drawer_item_body'>";
				    	data += "		<div class='for_edit'>";
				    	data += "			<h2>Alert Me...</h2>";
				    	data += "			<div class='drawer_edit_col'><h3>When this product is <em>marked down by at least:</em></h3> <select class='alert_percent'><option value=''>Select % Off</option><option value='10'>10% Off</option><option value='20'>20% Off</option><option value='30'>30% Off</option><option value='40'>40% Off</option><option value='50'>50% + Off</option></select></div>";
				    	data += "			<div id='divider_border'><span></span></div>";
				    	data += "			<div class='drawer_edit_col'><h3>When this product has reached this <em>Specific Price</em> or less</h3> <div class='txt_bx'><input type='text' class='alert_price' size='5' /><div class='alert_price_status'></div></div></div>";
				    	data += "			<input type='hidden' class='alert_change_to' value='percent' />";
				    	data += "			<input type='hidden' class='alert_id' value='"+item.id+"' />";
				    	data += "			<input type='hidden' class='alert_pid' value='"+item.product_key+"' />";
				    	data += "			<input type='hidden' class='alert_current_price' value='"+item.current_price+"' />";
				    	data += "		</div>";
				    	data += "	</div>";
				    	data += "	<div class='drawer_item_footer'>";
				    	data += "		<span>Alert me when it's "+(item.watching_type=="percent"?item.watching_text+" from $"+format_number(item.original_price):"$"+format_number(item.watching_price)+" or less")+"</span>";
				    	data += "		<div class='drawer_item_actions'>";
				    	data += "			<div class='edit'><div id='edit_l'></div><a class='dai_edit' href='/ajax/feature?f=alerts&action=edit-item&id="+item.id+"'>Edit</a><div id='edit_r'></div></div>";
				    	data += "			<div class='save_cancel'><div class='save_cancel_cont cancelit'><div id='cancel_l'></div><a class='dai_cancel' href='javascript:void(0)'>Cancel</a><div id='cancel_r'></div></div><div class='save_cancel_cont saveit'><div id='save_l'></div><a class='dai_save' href='/ajax/feature?f=alerts&action=save-item&id="+item.id+"'>Save</a><div id='save_r'></div></div></div>";
				    	data += "		</div>";
				    	data += "	</div>";
				    	data += "</div>";
				    }
		    	}
		    	else {
		    		data = "<div class='drawer_not_used'>Looks like you haven't set any Alerts!<span class='drawer_learn_how_link'><a href='/help?topic=drawer-alerts'>Learn How</a></span></div>";
		    	}

				$("#drawer_alerts .drawerContent").html(data);
				alert_minitext.html("Total: "+$("#drawer_alerts .drawer_item_container:visible").length);

				$("#drawer_alerts .drawer_item_container").hover(
					function(){ $(".drawer-alert-remove-item", this).show(); },
					function(){ $(".drawer-alert-remove-item", this).hide(); }
				);
				$("#drawer_alerts .drawer_item_container .drawer-alert-remove-item").click(function(){
					var item = $(this);
					var url = item.attr('href');
					$.ajax({async:false, dataType:"json", url:url,
						success:function(json){
							item.parents(".drawer_item_container").fadeOut('fast',function(){
								alert_minitext.html("Total: "+$("#drawer_alerts .drawer_item_container:visible").length);
							});
							url = url.replace("action=remove","action=undo");
							$("#drawer_alerts #alerts_status").html(" | <a id='drawer-alert-undo-item' href='"+url+"'>Undo</a>");
							$("#drawer-alert-undo-item").click(function(){
								$.ajax({async:false, dataType:"json", url:url,
									success:function(msg){
										$("#drawer_alerts #alerts_status").empty();
										item.parents(".drawer_item_container").fadeIn();
										alert_minitext.html("Total: "+$("#drawer_alerts .drawer_item_container:visible").length);
									}
								});
								return false;
							});
						},
						error:function(msg){ alert("Error: Could not remove this item in your alerts. Try again"); }
					});
					return false;
				});

			    $(".drawer_item_actions .dai_edit").click(function(){
	    			Init = $("#drawer_alerts .drawerContent");
	    			$(".drawer_item_body",Init).hide();
	    			$(".drawer_item_actions div.save_cancel",Init).hide();
	    			$(".drawer_item_actions div.edit",Init).show();
	    			$(".alert_price",Init).val('');
	    			$(".alert_percent",Init).val('');
	    			$(".alert_change_to",Init).val('percent');

			    	Alert = $(this).parents(".drawer_item_container");
			    	Alert.addClass("edit");
			    	saveit = $(".saveit",Alert);
			    	saveit.hide();

			    	$(".drawer_item_actions div.edit",Alert).hide();
			    	$(".drawer_item_body:hidden",Alert).show();
			    	$(".drawer_item_footer span",Alert).hide();
	    			$(".drawer_item_actions div.save_cancel:hidden",Alert).show();
				    $(".for_edit .alert_percent",Alert).change(function(){
				    	if(this.value>0) { $(".for_edit .alert_price",Alert).val(''); $(".for_edit .alert_change_to",Alert).val('percent'); saveit.show(); } else { saveit.hide(); }
				    });
					$(".for_edit input.alert_price",Alert).keyup(function(e){
						this.value = only_numbers(this.value);
						var n = parseFloat(this.value)||0;
						var c = parseFloat($(".for_edit .alert_current_price",Alert).val());
						if(n>0) {
							if(n<c) {
								$(".for_edit .alert_percent",Alert).val('');
								$(".for_edit .alert_change_to",Alert).val('desired');
								$(".for_edit .alert_price_status",Alert).hide();
								saveit.show();
							}
							else {
								$(".for_edit .alert_price_status",Alert).html("<b>Price Too High</b>").show();
								saveit.hide();
							}
						}
						else {
							$(".for_edit .alert_price_status",Alert).hide();
							saveit.hide();
						}
					});
				    return false;
			    });
	    		$(".drawer_item_actions .dai_save").click(function(){
			    	Alert = $(this).parents(".drawer_item_container");
			    	Edit = Alert.find(".for_edit");
	    			var alert_id = $(".alert_id",Edit).val();
	    			var alert_pid = $(".alert_pid",Edit).val();
	    			var alert_change_to = $(".alert_change_to",Edit).val();
	    			var alert_percent = $(".alert_percent",Edit).val();
	    			var alert_price = $(".alert_price",Edit).val();

	    			var wl_save = { f:"alerts", action:"edit-item", aid:alert_id, pid:alert_pid, wt:alert_change_to, wv:alert_percent, wp:alert_price }
	    			if(wl_save.wt=='percent') { wl_save.wp=''; } else { wl_save.wv=''; }
					$.ajax({type:"POST", dataType:"json", url:"/ajax/feature.php", data:wl_save,
						success:function(json){
			    			$(".drawer_item_body:visible, .drawer_item_actions div.save_cancel:visible",Alert).hide();
			    			$(".drawer_item_actions div.edit:hidden",Alert).show();
			    			$(".alert_price",Edit).val('');
			    			$(".alert_percent",Edit).val('');
			    			$(".alert_change_to",Edit).val('percent');
			    			A = json.payload;
			    			$(".drawer_item_footer span",Alert).html("Alert me when it's <em>"+(A.watching_type=="percent"?A.watching_text+"</em> from <em>$"+format_number(A.original_price):"$"+format_number(A.watching_price)+" or less")+"</em>").show();
			    			if(A.watching_met==true) {
			    				Alert.addClass("alert_meets_price");
			    			} else {
			    				Alert.removeClass("alert_meets_price");
			    			}
			    			Alert.removeClass("edit");
			    			def_color = $(".drawer_item_footer span em",Alert).css("color");
							$(".drawer_item_footer span em",Alert).css({color:'yellow'}).animate({opacity:0.5},1200,function(){
								$(".drawer_item_footer span em",Alert).css({color:def_color}).animate({opacity:1.0},'slow');
							});
						},
						error:function(msg){ alert("Error: Could not save your watch list item. Try again"); }
					});
					return false;
	    		});
	    		$(".drawer_item_actions .dai_cancel").click(function(){
			    	Alert = $(this).parents(".drawer_item_container");
			    	Alert.removeClass("edit");
	    			$(".drawer_item_body:visible, .drawer_item_actions div.save_cancel:visible",Alert).hide();
	    			$(".drawer_item_actions div.edit:hidden",Alert).show();
	    			$(".drawer_item_footer span",Alert).show();
	    			return false;
	    		});
		    }
		},
		wishlist: function(){
		    $.ajax({async:false, dataType:"json", url:"/ajax/feature?f=wishlist&action=get-items",
		    	success:function(json){ PAYLOAD = json; },
				error:function(json){ alert("Error: Could not find your Wish Lists. Try again"); }
		    });
		    if(PAYLOAD.error==null) {
				var wishlist_minitext = $("#drawer_wishlist #wishlist_minitext");
		    	var data = "";
		    	var get_items = {total:0, items:[]};
		    	get_items = PAYLOAD.payload || get_items;
		    	if(get_items.total>0) {
					for(var i=0; i<get_items.total; i++) {
						var item = get_items.items[i];
				    	data += "<div class='drawer_item_container'>"; // "+(item.watching_met==true?"alert_meets_price":"")+"
				    	data += "	<div class='drawer_item_head'>";
				    	data += "		<a class='drawer-wl-remove-item' href='/ajax/feature?f=wishlist&action=remove&wid="+item.id+"'></a>";
				    	data += "		<div class='for_display'>";
				    	data += "			<h2><a href='/details?"+item.product_key+"'>"+abbrev(item.title,85,true)+"</a></h2>";
				    	data += "			<div class='drawer_price_cont'><span>$"+format_number(item.current_price)+"</span><em>current price</em></div>";
				    	data += "		</div>";
				    	data += "	</div>";
				    	data += "	<div class='drawer_item_body'>";
				    	data += "		<div class='for_edit'>";
				    	data += "			<h2>Alert Me...</h2>";
				    	data += "			<div class='drawer_edit_col'><h3>When this product is <em>marked down by at least</em></h3> <select class='alert_percent'><option value=''>Select % Off</option><option value='10'>10% Off</option><option value='20'>20% Off</option><option value='30'>30% Off</option><option value='40'>40% Off</option><option value='50'>50% + Off</option></select></div>";
				    	data += "			<div id='divider_border'><span></span></div>";
				    	data += "			<div class='drawer_edit_col'><h3>When this product has reached this <em>Specific Price</em> or less</h3> <div class='txt_bx'><input type='text' class='alert_price' size='5' /></div></div>";
				    	data += "			<input type='hidden' class='alert_change_to' value='percent' />";
				    	data += "			<input type='hidden' class='alert_id' value='"+(item.reduced.alert && item.reduced.alert.id||0)+"' />";
				    	data += "			<input type='hidden' class='alert_pid' value='"+item.product_key+"' />";
				    	data += "		</div>";
				    	data += "	</div>";
				    	data += "	<div class='drawer_item_footer'>";
				    	if(item.reduced.alert) {
				    		data += "		<span>Alert me when it's "+(item.reduced.alert.type=="percent"?item.reduced.alert.text+" from $"+format_number(item.current_price):"$"+format_number(item.reduced.alert.price)+" or less")+"</span>";
						}
				    	data += "		<div class='drawer_item_actions'>";
				    	if(item.reduced.alert) {
				    		//data += "			<div class='edit'><div id='edit_l'></div><a class='dai_edit' href='/ajax/feature?f=alerts&action=edit-item&id="+item.reduced.alert.id+"'>Edit</a><div id='edit_r'></div></div>";
						}
				    	data += "			<div class='buy'><div id='cancel_l'></div><a target='_blank' class='dai_cancel wish_buy' href='"+item.buy_url+"'>Buy</a><div id='cancel_r'></div></div>";
				    	data += "		</div>";
				    	data += "	</div>";
				    	data += "</div>";
					}
		    	}
		    	else {
		    		data = "<div class='drawer_not_used'>You haven't added any products to your Wish List!<span><a href='/help?topic=drawer-wishlist'>Learn How</a></span></div>";
		    	}
			    $("#drawer_wishlist .drawerContent").html(data);
				wishlist_minitext.html("Total: "+$("#drawer_wishlist .drawer_item_container:visible").length);

				$("#drawer_wishlist .drawer_item_container").hover(
					function(){ $(".drawer-wl-remove-item", this).show(); },
					function(){ $(".drawer-wl-remove-item", this).hide(); }
				);
			    $("#drawer_wishlist .drawer-wl-remove-item").click(function(){
			    	var item = $(this);
			    	var url = item.attr('href');
				    $.ajax({async:false, dataType:"json", url:url,
				    	success:function(msg){
					    	url = url.replace("action=remove","action=undo");
					    	item.parents(".drawer_item_container").fadeOut('fast',function(){
								wishlist_minitext.html("Total: "+$("#drawer_wishlist .drawer_item_container:visible").length);
							});
					    	$("#drawer_wishlist #wishlist_status").html(" | <a class='drawer-wl-undo-item' href='"+url+"'>Undo</a>");
				    		$("#drawer_wishlist .drawer-wl-undo-item").click(function(){
							    $.ajax({async:false, dataType:"json", url:url,
							    	success:function(msg){
							    		$("#drawer_wishlist #wishlist_status").empty();
							    		item.parents(".drawer_item_container").fadeIn();
										wishlist_minitext.html("Total: "+$("#drawer_wishlist .drawer_item_container:visible").length);
							    	}
							    });
							    return false;
						    });
				    	},
						error:function(msg){ alert("Error: Could not remove this item in your wish list. Try again"); }
				    });
				    return false;
			    });
		    }
		},
		comparison: function(){
			var Drawer_Comparison_ViewPortFocus = function(){
				var grid_viewport = $("#comparison_grid").offset();
				var btn_position = $("#compare_btn_cont").offset();
				var actual_pos = (grid_viewport.top*2)+$("#comparison_grid").height();
				//if(btn_position.top>actual_pos) { $(document).scrollTop(50); }
			};
			//Drawer_Comparison_ViewPortFocus();

			var tab_compare_items = window.ComparisonTracker && ComparisonTracker.get_tab_items();
			var list = get_cookie("JC_compare_items") || '';
			var items = tab_compare_items || [];
			var html = "<div class='drawer_not_used drawer_coming_soon'>You haven't selected any products to compare yet!</div>";
			var grid_enabled = false;

			if(items.length>0) {
				$.ajax({async:false, dataType:"json", url:"/ajax/feature?f=compare&action=view-grid", data:{ items:items.join(",") },
					success:function(json){ html = json.payload; },
					error:function(json) { html = json.error; }
				});
			}
			var CompareGrid = $("#drawer_comparison #drawerCompareGrid");
			CompareGrid.html(html);
			var width = $("#comparison_grid",CompareGrid).length ? (items.length>4 ? 1200 : 900) : Drawer.config.comparison.width;
			Drawer.style_it({width:width});
			window.ComparisonTracker && ComparisonTracker.expand(width,900).active();

			$("#comparison_grid_show_all_rows").toggle(
				function(){
					$(this).text("Show Only Top 10");
					$("#comparison_table tbody tr.hide_row").removeClass('hide_row');
					return false;
				},
				function(){
					$(this).text("Show All Grid Rows");
					$("#comparison_table tbody tr:gt(9)").addClass('hide_row');
					return false;
				}
			);

			$("#comparison_table a.remove_compare_pid, #drawer_comparison #comparison_status a.undo_compare_pid").live("click",function(e){
				var pid = $(this).attr('rel');
				if($("#comparison_table #head-pid-"+pid).length) {
					if($(this).hasClass('remove_compare_pid')) {
						$("#comparison_table #head-pid-"+pid).addClass("removed").fadeOut();
						$("#comparison_table td.grid-pid-"+pid).addClass("removed").fadeOut();
						$("#drawer_comparison #comparison_status").html("<a href='javascript:void(0)' class='undo_compare_pid' rel='"+pid+"'>Undo</a>");
						ComparisonTracker.del(pid);
						ComparisonTracker.display_counter();
					}
					else {
						$("#comparison_table #head-pid-"+pid).removeClass("removed").fadeIn();
						$("#comparison_table td.grid-pid-"+pid).removeClass("removed").fadeIn();
						$("#drawer_comparison #comparison_status a.undo_compare_pid").hide();
						ComparisonTracker.add(pid);
						ComparisonTracker.display_counter();
					}
				}
				return false;
			});

			activate_sortable();
		}
	}
}

var PAYLOAD = {};
var LOCATOR = {
	active_hash_index:0,
	history:[],
	add: function(l){
		var lhash = l || '';
		var title = t || '';
		this.history.push(l);
		this.active_hash_index = this.history.length-1;
		this.hash(lhash);
		this.title(title);
	},
	remove: function(l){
		var count = 0;
		for(x in history) {
			if(l==x) { delete this.history[count]; }
			count++;
		}
	},
	go: function(l,r){
		var uri = l.toString() || '';
		var remove_hash = r || false;
		window.document.location.href = (remove_hash ? uri.replace('#','') : uri);
	},
	hash: function(h){
		var hash = h || null;
		window.location.hash = hash;
	},
	title: function(t){
		var title = t||'';
		document.title = title+" - jCompare";
	}
};

var Control = {
	zindex: null,
	start_timer: function(){
		window.jcompare_timer=new Date();
	},
	stop_timer: function(s){
		var s=s||'ms';
		var a=Math.floor((new Date()-window.jcompare_timer)/100)/10;
		if(a%1==0){a+=".0"}
		window.jcompare_timer=a+(s!=''?' '+s:'');
	}
}

var User = {
	email_change: function(req){
		var request = req || "resend";
		$.ajax({async:false, dataType:"json", url:"/ajax/feature?f=settings&action=email_change-"+request,
			success:function(json){
				var status = $("#drawer_settings #display_settingEmail .change_status");
				status.html(json.payload).show();
				if(request=="cancel") {
					$("#settings_change_email #email_change_status").fadeOut('fast');
					$("#settings_change_email #email_change_form").show();
					setTimeout(function(){
						status.fadeOut('fast').empty().html('');
					},8000);
				}
			},
			error:function(json){ alert("Error: Could "+request+" email change. Try again"); }
		});
	}
}


var JC_Facebook = {
	share_link:function() {
		u="http://www.jcompare.com"+replace_query_var("ref","facebook",remove_char(location.hash,"^#"));
		t=document.title;
		fb_link = 'http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t);
		facebook_share = window.open(fb_link,'sharer','toolbar=0,status=0,width=626,height=436');
		return false;
	},
	connect: {
		API_KEY:"4fa6f3402a7fa81a64c09b47ca5b4d57",
		uid:0,
		init: function(callback) {
			connect = this;
			if(window.FB_RequireFeatures && window.FB && typeof FB == "object") {
				FB_RequireFeatures(["XFBML"], function() {
					FB.init(connect.API_KEY,"/social/xd_receiver.html", {"ifUserConnected":connect.set_uid}); //"reloadIfSessionStateChanged":true ,
					connect.set_uid(get_cookie(connect.API_KEY+"_user"));
					connect.onload(connect.uid>0 ? true : false);
					if(typeof callback == "function") {
						callback();
					}
					debug("Facebook Connect is Ready.",'log',1);
					connect.check_modal_to_link_accounts();
				});
			}
			else {
				debug("Facebook Connect API (FB) not exist. Probably working offline.",'WARN',1);
			}
		},
		set_uid: function(id) {
			this.uid = id||0;
		},
		onlogin_ready: function(ret) {
			this.set_uid(get_cookie(this.API_KEY+"_user"));
			this.onload(this.uid>0 ? true : false);
			this.verify_account();
		},
		verify_account: function(ref) {
			var ref = ref||'fb';
			window.location.href = "/social/verify?ref="+ref+"&redirect="+escape(window.location.href);
		},
		logout: function() {
			if(this.uid>0) {
				FB.Connect.logout(function(){ window.location.href = "/logout?ref=fb"; });
			}
			else {
				window.location.href = "/logout";
			}
		},
		is_logged_in: function(d) {
			//1==FB.ConnectState.connected
			//2==FB.ConnectState.userNotLoggedIn
			//3==FB.ConnectState.appNotAuthorized
			status = 2;
			FB.ensureInit(function() {
				FB.Connect.get_status().waitUntilReady(function(status){
					if(!d){ return status; }
				});
				if(d){
					switch(status){case 1:l="connected";break;case 2:l="userNotLoggedIn";break;case 3:l="appNotAuthorized";break; default:l="Dunno";}
					debug("FB User: "+l,1);
				}
				return status;
			});
			return status;
		},
		onload: function(already_logged_into_facebook) {
			connect = this;
			FB.ensureInit(function() {
				is_logged_in = connect.is_logged_in();
				if(is_logged_in==FB.ConnectState.appNotAuthorized) {
					html = "<div id='facebook_connect_newuser'>";
					html += "<p>Facebook User? Log in and benefit from our advanced features</p>";
					html += "<p><fb:login-button size=\"medium\" length=\"long\" background=\"light\" onlogin=\"JC_Facebook.connect.onlogin_ready();\">Facebook Connect Inactive</fb:login-button></p>";
					html += "</div>";
					if($("#header #facebook_connect_newuser").length==0) {
						$("#header").append(html);
						FB.XFBML.Host.get_areElementsReady().waitUntilReady(function(){
							FB.XFBML.Host.parseDomTree();
							$("#header #facebook_connect_newuser").show();
						});
					}
				}
				if(is_logged_in==FB.ConnectState.connected) {
					if(get_cookie("SocialConnectedChecked")!="Y") {
						connect.verify_account();
					}
				}
			});
		},
		prompt_permission: function(permission) {
			connect = this;
			var permissions = permission || "publish_stream, read_stream, email, read_mailbox, offline_access, create_event, rsvp_event, sms, status_update, photo_upload, video_upload, create_note, share_item";
			FB.ensureInit(function() {
				FB.Facebook.apiClient.users_hasAppPermission(permissions,function(result){
					if(result==0) {
						FB.Connect.showPermissionDialog(permissions, function(){
							create_cookie("FB_C_NU","N",30);
						});
					}
				});
			});
			return;
		},
		check_modal_to_link_accounts:function(){
			// Modal overlay...
			var facebook_link = $("#facebook_link_account.modal");
			if(facebook_link.length>0) {
				facebook_link.open_overlay({addClass:'modal_facebook', closeOnClick:false, closeOnEsc:false, top: 170});
			}

			$("#facebook_link_account.modal button.yes_no").click(function(){
				var yes = this.id=="yes" ? true : false;
				var p = $(this).parent('p');
				if(yes) {
					p.html('Linking accounts ...');
				}
				else {
					p.html('Creating seperate accounts ...');
				}
				facebook_link.close();
				JC_Facebook.connect.link_existing_account(yes);
			});
			$("#link_social_account #help").click(function(){
				$("#link_social_account #help_link_accounts").fadeIn();
				$(this).css('color','gray').css('border-color','gray');
				return false;
			});

		},
		link_existing_account: function(set) {
			connect = this;
			$.ajax({async:false, dataType:"json", url:"/ajax/feature?f=social&action=link-accounts", data:{app:"facebook", userid:get_cookie(this.API_KEY+"_user"), merge:(set?"Y":"N")},
				success:function(json){
					if(json.error==null) {
						$("#login_success #link_social_account").fadeOut();
						connect.verify_account();
					}
					else {
						var post_action = "&post_action=social-link-facebook&post_data=";
						var p_redirect = "p_redirect="+escape(replace_query_var("ref","fb-connect",window.location.href))+post_action;
						$.fn.colorbox({href:"/login?js=0&facebook=0&register=0&"+p_redirect, open:true, iframe:true, width:530, height:440});
					}
				},
				error:function(json) { alert("Ooops, something happened!"); }
			});
		},
		publish_feed_story: function(form_bundle_id, template_data) {
			// Load the feed form
			FB.ensureInit(function() {
				FB.Connect.showFeedDialog(form_bundle_id, template_data);
				//FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

				// hide the "Loading feed story ..." div
				$("#feed_loading").hide();
			});
		},
		show_feed_checkbox: function() {
			FB.ensureInit(function() {
				FB.Connect.get_status().waitUntilReady(function(status) {
					if(status != FB.ConnectState.userNotLoggedIn) {
						// If the user is currently logged into Facebook, but has not
						// authorized the app, then go ahead and show them the feed dialog + upsell
						checkbox = $("#publish_fb_checkbox");
						if(checkbox) {
							checkbox.show();
						}
					}
				});
			});
		}

	}
}

var GlobalSearch = {
	init: function() {
		$("#global_search_input").autocomplete("/ajax/autocomplete?f=home", {
			delay:900, get_return:false, selectFirst: false, matchContains: true, resultsClass:"global_ajax_ac_results", scroll:false, width:585, clickable:false, display_header:true, display_footer:true,
			formatItem: header_global_search_display,
			before: function(){
				window.ac_globalsearch_query_txt=$("#global_search_input").val();
				//$("#tab_nav li a.tip_tab_exists").removeClass("tip_tab_exists");
			},
			after: GlobalSearch.get_product_details
		});
		$("#global_search_input").keyup(function(e){
			e.stopPropagation();
			input = $(this);
			var q = trim(input.val());
			if(e.keyCode==13) {
				if(window.autocomplete_ajax) {
					var running_ajax = window.autocomplete_ajax;
					running_ajax.abort();
				}
				if(Tabber && Tabber.create && Search && Search.query_search) {
					tab_exists = Tabber.get_history_by_query(q);
					if(tab_exists!=null && tab_exists.id && tab_exists.id>0 && $("#tab_content div#tab-"+tab_exists.id+".tab").length==1) {
						$("#tab_nav li a.tip_tab_exists").removeClass("tip_tab_exists");
						input.val('Switching Views...');
						Tabber.view(tab_exists.id);
						input.val('').blur();
					}
					else {
						input.val('Searching...');
						$("#ac_autocomplete.global_ajax_ac_results").hide();
						title = addslashes(q);
						href = "/search?ref=gs&q="+escape(q);
						Tabber.create(href,escape(q),title,"search");
						Tabber.view();
						Tabber.content("<div class='no_results_found'>Searching through products for... <strong>\""+q+"\"</strong><span><img src='/images/ajax_loader.gif' border='0' /></span></div>");
						var query_data = Search.query_search(q,"showsmartfilters=1");
						Tabber.content(query_data.result);
						Search.init();
						input.val('').blur();
						Tracking.ready().google().trackEvent("GlobalSearch","Search",q);
					}
				}
				return false;
			}
		});
	},
	get_product_details: function(){
		$("#ac_autocomplete.global_ajax_ac_results .ac_inner li").live("click",function(e){
			e.stopPropagation();
			var href = $(".tab-detail", this).attr('href') || '';
			var title = $(".tab-detail", this).text() || '';
			if(Tabber.create && Search.query_search) {
				var q = query_var("q",href);
				$("#global_search_input").val('Retrieving Details...');
				$("#ac_autocomplete.global_ajax_ac_results").hide();
				href = href+"&showhtml=prices&showsmartfilters=1";
				title = addslashes(title);
				Tabber.create(href,escape(q),title,"details");
				Tabber.view();
				Tabber.content("<center><br /><br /><br />Loading product details...<br /><br /><img src='/images/ajax_loader.gif' border='0' /><br /><br /><br /></center>");
				var data = Search.query_search(q,null,href);
				Tabber.content(data.result);
				Search.init();
				$("#global_search_input").val('').blur();
				Tracking.ready().google().trackEvent("GlobalSearch","Details",title).trackPage(href);
			}
			return false;
		});
	}
};

var Tracking = {
	init_from_ready:false, is_ready:false, debug:false,
	init:function(){
		// Do not do tracking in local env...
		if(JC_Bootloader.connection==false) {
			debug("Tracking analytics disabled if offline. (env: "+document.domain+")", "WARN",1);
			return false;
		}
		this.is_ready = false;
		return this.init_from_ready ? true : false;
	},
	_debug:function(){
		this.debug = true;
		return this;
	},
	ready: function(callback){
		this.init_from_ready = true;
		this.is_ready = this.init();
		if(callback && typeof callback=="function") { callback(); }
		return this;
	},
	check_if_ready:function(){
		if(!this.is_ready) {
			debug("Tracking requires .ready() method first.","error",1);
			return false;
		}
		return true;
	},
	// Google Analytics
	google: function(args){
		global = this;
		if(!global.check_if_ready()){return false;}
		var args = args && typeof args=="object"||{};
		var option = {_gat_tracker_id:"UA-11252405-1", domain:args.domain||".jcompare.com", page:args.page||null};

		this.init = function() {
			if(!window.pageTracker && !window._gat) {
				$.getScript((("https:"==document.location.protocol)?"https://ssl.":"http://www.")+"google-analytics.com/ga.js", function(){
					if(window._gat != undefined) {
						window.pageTracker = _gat._getTracker(option._gat_tracker_id);
						window.pageTracker._setDomainName(option.domain);
						window.pageTracker._trackPageview(option.page);
						global.debug ? debug("Tracking with Google Analytics", 1) : null;
					}
					else {
						debug("Tracking disabled Google Analytics",'warn',1);
					}
				});
			}
			return this;
		};

		this.trackEvent = function(c,a,l,v){
			if(!window.pageTracker) { debug("GA must be init.",'error',1); return false; }
			var opt = { category:c||'', action:a||'', label:l||'', value:v||0 }
			window.pageTracker._trackEvent(opt.category,opt.action,opt.label,opt.value);
			global.debug ? debug("GA tracking event: "+opt.category+" > "+opt.action+" > "+opt.label+" > "+opt.value, 1) : null;
			return this;
		};
		this.trackPage = function(page){
			var page = page||null;
			window.pageTracker._trackPageview(page);
			global.debug ? debug("GA tracking page: "+page, 1) : null;
		};

		return this.init();
	}
};

var Map = {
	google: {
		API_KEY: "ABQIAAAA2ikY721G7o18Vc4CZ8NqwRRyJGbXqoxEFFLDTcSU31CGBnPCWxRyItBGAmnKM4c88nUlzAprrDHrlw"
	}
}

var Feedback = {
	domain: '', is_ready:false,
	init:function(){
		// Do not do feedback external scripts in local env...
		if(JC_Bootloader.connection==false) {
			debug("Feedback external scripts disabled if offline. (env: "+this.domain+")", "WARN",1);
			return false;
		}
		return this;
	},
	getsatisfaction: function(){
		var feedback_widget_options = {};
		var browser=navigator.appName;
		feedback_widget_options.display = "overlay";
		feedback_widget_options.company = "jcompare";
		feedback_widget_options.placement = "left";
			if ((browser=="Microsoft Internet Explorer"))
  				{
				feedback_widget_options.color = "#222222";
  				}
			else
  				{
				feedback_widget_options.color = "rgba(11,11,11,0.70)";
  				}
		feedback_widget_options.style = "idea";
		if(window.GSFN && typeof GSFN == "object") {
			var feedback_widget = new GSFN.feedback_widget(feedback_widget_options);
		}
		return this;
	}
};

// jQuery Custom Seletors and Mini-plugins...
$(function(){
	// expressions
	$.expr[':'].setdisable = function(element){
		return $(element).attr('disabled','disabled');
	};

	// plugins
	$.fn.disable = function(options) {
		return $(this).attr('disabled','disabled');
	};

	$.fn.open_overlay = function(opt,callback) {
		var options = typeof opt==="object" && opt||{};
		var g = $(this);
		window.loading_indicator = function(on){
			var on = on || false;
			if(window.overlay) {
				if(on) {
					window.overlay.html("<div id='loading'><div>Loading Awesome Information ...</div></div>");
					window.overlay.find("#loading").css({opacity:0.7});
				}
				else {
					window.overlay.find("#loading").fadeOut('fast');
				}
			}
		};
		if($.fn.overlay && g.length) {
			options.url = options.url || null;
			options.load = options.load || null;
			options.addClass = options.addClass || '';
			options.wait = options.wait || true;

			if(options.url!='' && options.url!=undefined && options.url!=null) {
				g.attr('href',options.url);
			}
			else if(options.url==null && g.attr('href')!='') {
				options.url = g.attr('href');
			}

			// config overlay
			options.closeOnClick = options.closeOnClick
			options.closeOnEsc = options.closeOnEsc;
			options.speed = options.speed || 'fast';
			options.top = options.top || '10%';
			options.left = options.left || 'center';
			options.width = options.width || 600;
			options.height = options.height || 500;
			options.loadSpeed = options.loadSpeed	 || 100;
			options.opacity = options.opacity || 0.5;

			// TODO: fix this hack, emulating the $(this) for anchor <A> thus may not capture HREF or INNERHTML.
			a_c = {href: g.attr('href'), html: g.html() };
			g = $("<a>");
			g.attr('href',a_c.href);
			g.html(a_c.html);
			// end hack

			window.overlay_active = g.overlay({
				api:true, target:"#overlay",
				closeOnClick:options.closeOnClick, closeOnEsc:options.closeOnEsc,
				speed:options.speed, top:options.top, left:options.left,
				expose: { color:'#333', loadSpeed:options.loadSpeed, opacity:options.opacity },
				onBeforeLoad: function(e) {
					window.overlay = $("#overlay");
					window.overlay.removeAttr('class').html("<span />");
					options.wait ? window.loading_indicator() : null;

					if(options.addClass!='' && options.addClass!=null) {
						window.overlay.addClass(options.addClass);
					}
					var A = this.getTrigger();
					var href = A.attr("href");
					var title = A.attr("title");

					if(href!='' && href!=undefined && href!=null) {
						if(options.load=="inline") {
							//debug("Overlay ajax.load",1);
							window.overlay.load(href);
						}
						else {
							//debug("Overlay iframe",1);
							window.overlay.css({width:options.width, height:options.height});
							window.overlay.addClass("iframe").append("<iframe frameborder='0' scrolling='auto' src=\""+href+"\" onLoad='window.loading_indicator(false);'></iframe>");
						}
					}
					else {
						//debug("Overlay modal",1);
						window.overlay.append(A.html());
					}
					//debug("Overlay: onBeforeLoad",1);
				},
				onLoad:function(){
					if(!window.overlay.hasClass("iframe")) {
						options.wait ? window.loading_indicator(false) : null;
					}
					window.overlay.addClass("active");
					//debug("Overlay: onLoad",1);
					return false;
				},
				onClose:window.close_overlay
			});

			if(window.overlay && jQuery.expose && window.overlay.expose() && window.overlay.expose().isLoaded()) {
				window.overlay.removeAttr('class').html("<span />");
				options.wait ? window.loading_indicator() : null;
				//debug("window.overlay is already opened...",1);
				if(options.addClass!='' && options.addClass!=null) {
					window.overlay.addClass(options.addClass);
				}
				window.overlay.css({top:options.top, left:options.left});
				if(options.url!='' && options.url!=undefined && options.url!=null) {
					if(options.load=="inline") {
						//debug("existing Overlay ajax.load",1);
						window.overlay.load(options.url);
					}
					else {
						//debug("existing Overlay iframe",1);
						window.overlay.css({width:options.width, height:options.height});
						window.overlay.addClass("iframe").append("<iframe frameborder='0' name='second' scrolling='no' src='"+options.url+"' onLoad='window.loading_indicator(false);'></iframe>");
					}
				}
				else {
					//debug("existing Overlay modal",1);
					window.overlay.append(g.html());
				}
				if(!window.overlay.hasClass("iframe")) {
					options.wait ? window.loading_indicator(false) : null;
				}
				//debug("Overlay: opening existing overlay",1);
			}
			else {
				if(options.url!='' && options.url!=undefined && options.url!=null) {
					g.removeClass('modal');
				}
				window.overlay_active.load();
				//debug("Overlay: loading new overlay",1);
			}
		}
		if(callback) { callback(); }
		return g;
	};
	window.close_overlay = function(){
		if(window.overlay_active && window.overlay && window.overlay.hasClass('active')) {
			window.overlay_active.close();
			window.overlay.expose().close();
		}
		//debug("Overlay: window.close_overlay",1);
	};

	$("#debug_control a#show_debug_messages").toggle(function(){ $(this).text("Hide Debug Messages"); $(".debug").show(); }, function(){ $(this).text("Show Debug Messages"); $(".debug").hide(); } );
});

var JOB_online_status = function(){
	if($("#login_success").length){ //get_cookie("JC_MLT")>0 && validate_email(get_cookie("JC_L_rct"))) {
		$.getJSON("/ajax/feature?f=onlinestatus",function(json){
			if(json.error!=null) {
				jc_login = "<div class='modal' id='jc_prompt_login'><div class='modal_body'>";
				jc_login += "<h2>You are sign-</h2>";
				jc_login += "</div></div>";
				$('body').append(jc_login);
				$("#jc_prompt_login.modal").overlay({
					api: true,
					closeOnClick: false,
					closeOnEsc: false,
					speed: 'fast',
					top: 170,
					expose: {
						color: '#333',
						loadSpeed: 200,
						opacity: 0.9
					}
				}).load();

				$("#link_social_account.modal button.yes_no").click(function(){
					var yes = this.id=="yes" ? true : false;
					var p = $(this).parent('p');
					if(yes) {
						redirect = "/login?redirect="+escape(window.location.href);
					}
					else {
						redirect = window.location.href;
					}
					window.location.href = redirect;
				});
			}
			//else { debug("I am still online ... phew!"); }
		});
	}
};

// Page Script to load in index/homepage...
var PageScript_homepage = function(){
	DEBUG_LEVEL(0);
	//JC_Bootloader.job("online", 30, JOB_online_status);
	JC_Bootloader.js("search.js");
	JC_Bootloader.ready(function(){
		JC_Facebook.connect.init();
		Drawer.ready();
		//JC_Bootloader.load_js("http://tweetboard.com/tb.js?v=1.0&user=jcompare");

		$("#q").autocomplete("/ajax/autocomplete?f=home&abbrev=30", {
			resultsClass:"index_ac_results", scroll:false, clickable:false, selectFirst:false, matchContains:true,
			display_header:true, display_footer:true, display_inner_right:true,
			formatItem: index_global_search_display_preview,
			before: function(){ Control.start_timer(); window.ac_indexsearch_query_txt=$("#q").val(); },
			after: function(){
				$(document).find("input.ac_input").unbind(($.browser.opera?"keypress":"keydown"));
				$("#ac_autocomplete.ac_inner_right").html("<div id='preview_area'></div>");
				display_search_preview();
				// display for first LI...
				$("#ac_autocomplete.ac_all .ac_inner_right").html($(".preview:hidden","#ac_autocomplete .ac_list li:first").html());
				Control.stop_timer();
			}
		});
		$("#search").submit(function(){
			var q = trim($(this).find("#q").val()||'');
			var title = addslashes(q);
			var hash = "/search?ref=home&q="+escape(q);
			var json_tab_cookie = {id:1, hash:hash, q:escape(q), title:title, ref:"search"};
			for(var i=1; i<=5; i++) { delete_cookie("TAB:"+i); }
			delete_cookie("TAB:last-active");
			delete_cookie("TAB:hash");
			create_cookie("TAB:1", JSON.stringify(json_tab_cookie));
			Tracking.ready().google().trackEvent("Home","Search",title);
			window.document.location.href = "/search?#"+hash;
			return false;
		});
		$("#search #home_btn").click(function(){ $("#search").trigger("click"); });
	});
}

// TEMP LOCATION, move into an object.
$(function(){
	// Modal overlay...
	$("#message_after_registration.modal").open_overlay({addClass:'first_time_user waiting_autoclose',wait:false}, function(){
		$("#show_tutorial").live("click",function(){
			window.close_overlay();
			return false;
		});
		return false;
	});
	$("#email-change-confirmed.modal,#email-change-cancelled.modal").open_overlay({addClass:'first_time_user waiting_autoclose'});
});

/* Global Settings */
if(document.images) { preload=new Image();preload.src="/images/ajax_loader.gif"; }

function validate_email(e) {
	var e = e || ''; e = trim(e.toString());
	var v = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return (v.test(e)?true:false);
}
function alphanum(s) { s=s||''; s=s.toString(); return s.replace(/[^a-zA-Z0-9\,\.\/\(\)\&\'\"\:\ ]/gi,""); }
function remove_char(s,r) { s=s||''; r=r||''; s=s.toString(); r=r.toString(); var re=new RegExp(r,'gi'); return s.replace(re,""); }
function only_number(s) { s=s||''; s=s.toString(); return s.replace(/[^0-9\.]/gi,""); }
function only_numbers(s) { return only_number(s); }
function trim(s) { return jQuery.trim(s); }
String.prototype.toTitleCase = function() {
	s = this.toString();
	return s.substr(0,1).toUpperCase()+s.substr(1);
}
function htmlentities(s) { s=s.replace(/\"/g,'&quot;');s=s.replace(/\'/g,'&apos;');return s; }
function addslashes(s) { s=s.replace(/\"/g,'\"');s=s.replace(/\0/g,'\\0');return s; }
function stripslashes(s) { s=s.replace(/\\'/g,'\'');s=s.replace(/\\"/g,'"');s=s.replace(/\\0/g,'\0');s=s.replace(/\\\\/g,'\\');return s; }
function decimal(str,precision,exclude) {
	var str = parseFloat(str)||'', precision = parseInt(precision)||2, exclude = exclude||false;
	var ret = (typeof str=="number" ? str.toFixed(precision) : '');
	ret = (exclude ? ret.replace('.00','') : ret);
	return ret;
}
function format_number(str) {
	str = str || '';
	str = str.toString().replace(/\$|\,/gi,'');
	if (isNaN(str)) str = '0';
	sign = (str == (str = Math.abs(str)));
	str = Math.floor(str * 100 + 0.50000000001);
	cents = str % 100;
	str = Math.floor(str / 100).toString();
	if(cents < 10) cents = '0' + cents;
	for(var i = 0; i < Math.floor((str.length - (1 + i)) / 3); i++) {
		str = str.substring(0, str.length - (4 * i + 3)) + ',' + str.substring(str.length - (4 * i + 3));
	}
	return (((sign) ? '' : '-') + str + '.' + cents);
}
function abbrev(s,n,a,t) {
	var s=s||'', n=parseInt(n)||20, a=a||false; t=t||'', s=s.toString(); t=t.toString(); x=s;
	if(s.length>0 && n>0 && s.length>n && t=='') {
		x = '';
		for(i=0;i<n;i++) { x += s[i]; }
		x = trim(x)+"...";
	}
	if(t!='') { s=t; }
	s = (a==true?"<abbr title=\""+s.replace(/\"/g,"'")+"\">"+x+"</abbr>":x);
	return s;
}
function unique_array(a) {
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++)
   {
      for(var x = 0, y = r.length; x < y; x++)
      {
         if(r[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
}

function query_var(key,query) {
	var query = query && query.toString() || window.location.search.substring(1);
	var vars = query.split("&");
	var ret = '';
	for(var i=0; i<vars.length; i++) {
		var pair=vars[i].split("=");
		if(pair[0]==key) { ret = pair[1]; break; }
	}
	return ret;
}
function replace_query_var(key,replace,query,add_it) {
	var query = query && query.toString() || window.location.search.substring(1);
	var found = false, qs = '', url = '', new_vars = [], add_it = add_it||false;
	if(query.indexOf('?')>-1) {
		var original = query.split("?");
		url += original[0]+"?";
		for(var x=1; x<original.length; x++) { qs += original[x]; }
		query = qs;
	}
	var old_vars = query.split("&");
	for(var i=0; i<old_vars.length; i++) {
		var pair=old_vars[i].split("=");
		if(pair[0]==key) { new_vars.push(key+"="+replace); }
		else { new_vars.push(pair.join('=')); }
	}
	if(add_it) {
		new_vars.push(key+"="+replace);
	}
	var params = new_vars.join('&');
	//if(!params.match(/^\?/gi)) { params = "?"+params; }
	url = url+params;
	return url;
}
function replaceDomainURL(s) {
	s = s.replace('http://dev.jcompare.com','');
	s = s.replace('http://www.jcompare.com','');
	s = s.replace('http://jcompare.com','');
	return s;
}

function login_first() {
	$('.drawer:visible').hide();
	$('#navBar a').removeClass("active");
	$('ul#navBar li a#register').addClass("active");
	$('#drawer_inner_wrap').animate({width: (Drawer.config.register.width)+'px'}, 500);
	$('#drawer_register.drawer').fadeIn('slow');
	return false;
}

function create_cookie(n,v,e,d){
	if(n!=null && n!='') {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+e);
		var c = n+"="+encodeURIComponent(v)+((e==null||e=='')?"":";expires="+exdate.toGMTString());
		document.cookie = c;
        //debug("create cookie: "+c,1);
	}
	else { debug("Cannot create cookie = name: "+n||''+" | value: "+v||'','warn',1); }
	return "";
}

function delete_cookie(n,p) {
	if(n!='' && n!=null) {
		var date = new Date(); date.setTime(date.getTime()+(-3*24*60*60*1000));
		var c = n+"=1; expires="+date.toGMTString()+"; path="+(p||'/');
		document.cookie = c;
		//debug("delete cookie: "+c,1);
	}
}
function get_cookie(n,d) {
	var name=n||'', _default=d||'';
	if(document.cookie.length>0) {
		c_start=document.cookie.indexOf(name + "=");
		if(c_start!=-1) {
			c_start=c_start+name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if(c_end==-1) { c_end=document.cookie.length; }
			return decodeURIComponent(document.cookie.substring(c_start,c_end));
		}
	}
	return unescape(_default.toString());
}

function InitPageScripts(script_func) {
	var script_func = script_func || "";
	var PageScript_Scriptname = "PageScript_"+trim(script_func.toString());
	if(PageScript_Scriptname != undefined) {
		eval("window.JC_RunPageScript = window."+PageScript_Scriptname);
		if(JC_RunPageScript && typeof JC_RunPageScript == "function") {
			window.JC_RunPageScript();
		}
		else {
			debug("Page Script Not Exist: "+PageScript_Scriptname, "error");
		}
	}
	else {
		debug("Page Script Invalid Param: "+PageScript_Scriptname, "error");
	}
}

/* Autocomplete and index methods */
function index_global_search_display_preview(d) {
	var query = window.ac_indexsearch_query_txt||'';
	var d = { num:d[0], price:d[1], pid:d[2], name_abbrev:d[3], name_full:d[4], subcat_id:d[5], subcat_name:d[6], maincat_name:d[7], buy_url:d[8], image_url:d[9], description:d[10] };
	var names = (d.name_abbrev!='' ? "<span>"+d.name_abbrev+"</span><span class='title_full'>"+d.name_full+"</span>" : "<span>"+d.name_full+"</span>");
	var result  = "<div class='homepage'>";
		result += "<h1><a href=\"/search?q="+query+"&pid="+d.pid+"\">"+names+"</a></h1> <span class='price_sm'>"+d.price+"</span>";
		result += "<div class='preview'><span class='cat'>"+d.subcat_name+"</span><img class='pic' src='"+d.image_url+"' /><span class='price'>"+d.price+" <b>Best Price</b></span><div id='ac_break'></div>"+d.description+"</div>";
		result += "</div>";
	return result;
}
function header_global_search_display(d) {
	var query = window.ac_globalsearch_query_txt||'';
	var d = { num:d[0], price:d[1], pid:d[2], name_abbrev:d[3], name_full:d[4], subcat_id:d[5], subcat_name:d[6], maincat_name:d[7], buy_url:d[8], image_url:d[9], description:d[10] };
	var names = d.name_full;
	var result  = "<span class='tab-detail' href=\"/search?q="+query+"&pid="+d.pid+"\">"+names+"</span> <span class='price'>"+d.price+"</span>";
	return result;
}

function display_search_preview(){
	$("#ac_autocomplete .ac_list li").live("mouseover",function(e){
		if($(".preview:hidden", this).length==1) {
			var preview = $(".preview:hidden", this).html();
			$("#ac_autocomplete.ac_all .ac_inner_right").html(preview);
		}
	}).live("click",function(e){
		var query = window.ac_indexsearch_query_txt||'';
		var title = $("h1 a", this).text();
		title = addslashes(title);
		var pid = $("h1 a", this).attr('pid');
		var href = replaceDomainURL($("h1 a", this).attr('href'));
		var json_tab_cookie = { id:1, hash:href, q:escape(query), title:title, ref:"search" };
		for(var i=1; i<=5; i++) { delete_cookie("TAB:"+i); }
		delete_cookie("TAB:last-active");
		delete_cookie("TAB:hash");
		create_cookie("TAB:"+json_tab_cookie.id, JSON.stringify(json_tab_cookie));
		Tracking.ready().google().trackPage(href);
		window.document.location.href = "/search?ref=h-ac#"+href;
		return false;
	});
    $("input#q").live(($.browser.opera?"keypress":"keydown")+".autocomplete", function(e){
    	if(e.keyCode==38 || e.keyCode==40) {
			$("#ac_autocomplete").addClass('li-active-keydown');
			var preview = $("#ac_autocomplete .ac_list li.ac_over .preview:hidden").html();
			$("#ac_autocomplete.ac_all .ac_inner_right").html(preview);
    	}
    	// FIXME: when keydown on LI then keypress ENTER on result, it doubles the href  on var AC_D.
    	else if(e.keyCode==13) {
			if($("#ac_autocomplete").hasClass("li-active-keydown")) {
				$("#ac_autocomplete.li-active-keydown .ac_list li").trigger('click');
				return false;
			}
    	}
    });
	return false;
}

function activate_sortable() {
	// Capture the mouse x and y positions (only Y is needed for this task but there's no harm in getting both axis.
	// Declare global variables so they can be accessed anywhere.
	// The lastX and lastY variables will be used to keep track of which direction the mouse is heading
	// when moving the TR elements
	var mouseX, mouseY, lastX, lastY = 0;

	// This function captures the x and y positions anytime the mouse moves in the document.
	$().mousemove(function(e) { mouseX = e.pageX; mouseY = e.pageY; });

	//IE Doesn't stop selecting text when mousedown returns false we need to check
	// That onselectstart exists and return false if it does -- we won't check if the browser is IE
	// As thy may very well change this at some point.
	var need_select_workaround = typeof $(document).attr('onselectstart') != 'undefined';

	// The first order of business is to bind a function to the mousedown event
	// on all TR elements inside the tbody. I am using the jQuery live() function because my content is loaded through
	// ajax. simply use mousedown() if you do not need to load this on dynamic functions
	var row = $('#comparison_table tbody tr.product_row td.feature_label');
	row.live('mousedown', function (e) {
		var MOVABLE = $(this);
		MOVABLE.css('cursor','move');
		//MOVABLE.addClass('comparison_row_movable');
		// Store the current location Y axis position of the mouse at the time the
		// mouse button was pushed down. This will determine which direction to move the table row
		lastY = mouseY;

		// store $(this) tr element in a variable to allow faster access in the functions soon to be declared
		var tr = MOVABLE.parents('tr');

		// This is just for flashiness. It fades the TR element out to an opacity of 0.2 while it is being moved.
		tr.fadeTo('fast', 0.2);

		// jQuery has a fantastic function called mouseenter() which fires when the mouse enters
		// This code fires a function each time the mouse enters over any TR inside the tbody -- except $(this) one
		$('tr.product_row', tr.parent() ).not(tr).mouseenter(function(){
			// Check mouse coordinates to see whether to pop this before or after
			// If mouseY has decreased, we are moving UP the page and insert tr before $(this) tr where
			// $(this) is the tr that is being hovered over. If mouseY has decreased, we insert after
			if (mouseY > lastY) {
				$(this).after(tr);
			} else {
				$(this).before(tr);
			}
			// Store the current location of the mouse for next time a mouseenter event triggers
			lastY = mouseY;
			tr.addClass("movedme");
		});

		// Now, bind a function that runs on the very next mouseup event that occurs on the page
		// This checks for a mouse up *anywhere*, not just on table rows so that the function runs even
		// if the mouse is dragged outside of the table.
		$('body').mouseup(function () {
		   //Fade the TR element back to full opacity
		   tr.fadeTo('fast', 1);

		    var existing_features_moved = get_cookie("comparison_sorted_features").split(",");
			var features_moved = $.map($('#comparison_table tbody tr.movedme'), function(e){ return $(e).attr('id').replace('F___','').replace(/_/gi,' '); });
			for(x in features_moved) {
				if($.inArray(features_moved[x], existing_features_moved)==-1) {
					existing_features_moved.push(features_moved[x]);
				}
			}
			create_cookie("comparison_sorted_features",existing_features_moved.join(),30);

		   // Remove the mouseenter events from the tbody so that the TR element stops being moved
		   MOVABLE.unbind('mouseenter');
		   //MOVABLE.removeClass('comparison_row_movable');
		   $('tr.product_row', tr.parent()).unbind('mouseenter');
		   // Remove this mouseup function until next time
		   $('body').unbind('mouseup');

			// Make text selectable for IE again with
			// The workaround for IE based browsers
			if(need_select_workaround) {
				$(document).unbind('selectstart');
			}

		});

		// This part if important. Preventing the default action and returning false will
		// Stop any text in the table from being highlighted (this can cause problems when dragging elements)
		e.preventDefault();

		// The workaround for IE based browers
		if (need_select_workaround) {
			$(document).bind('selectstart', function () { return false; });
		}

		return false;

	})
	.live('mouseup',function(e){
		$(this).css('cursor','default');
	})
	.mouseover(function(){
		$(this).addClass('comparison_row_movable');
	})
	.mouseout(function(){
		$(this).removeClass('comparison_row_movable');
	});

}

var lighbox_close = function(){
	if($.fn.overlay && window.overlay_active) {
		window.overlay_active.close();
	}
}
$(document).ready(function() {
	var doFadeIn = function() {
		$('#index_fader').css({ opacity:0, visibility:'visible'}).fadeTo(700,1);
	};
	$('body').one('mousemove',doFadeIn);	
});