$(function(){	 

	var change_zip_html = '';
	$("form.change-location").submit( function(){
		var zip = $("form.change-location input[name=zipcode]");
		var jobs = $("input.diy-id");
		var jobs_param = ''; 
		var loc = $("input[name=location]");
		var ajaxLoader = "<img src='/images/small-ajax-loader.gif' class='spinner'/>"; 
		
		$.each(jobs,function(){
			jobs_param += this.value +" "; 
		});
		jobs_param = escape(jobs_param); 
		
		if($(zip).val().length <= 3){return false;$(zip).focus();}	 	
		$(ajaxLoader).appendTo($('.zip-label'));
		$.getJSON('/default/get_zip_info',{zip:$(zip).val(),jobs:jobs_param},function(data){						
			if(data != 0){ 
				$(".location").html(data.city+', '+data.state);
				var shops_in_the_area = parseInt(data.shops_in_the_area); 
				var shop_count_txt = '';  
				if(shops_in_the_area > 1){   
					shop_count_txt = ' shops';  
				}else{
					shop_count_txt = ' shop';
				}
				var shop_count = data.shops_in_the_area ? data.shops_in_the_area : '0';   
				
				if(data.shops_in_the_area >= 100){ 
					shop_count = '100+'; 				
				}  
				
				$('.area-shop-count').html(shop_count);
				
				$('.shop-desc').html(shop_count_txt); 
				
				$("#change-zip-dialog").fadeOut();				
				$(loc).each(function(){ 
						$(this).val($(zip).val()); 
				}); 
				$(zip).val(''); 
				$('.spinner').remove();
			}else{   
				$('.spinner').remove();
				alert("Invalid zip"); 
				$(zip).focus().val('');  
			} 
		});
		return false; 
	});
	$("#overlay").click(function(){
		closeVehicleSelection();  
	}); 
	$(".change-zip").live("click", function() {
		if ($("#change-zip-dialog").css("display") != "none") { return; }
		$("#change-zip-dialog").fadeIn('fast').css({
			top:  $(this).offset().top  - $("#all").offset().top + $(this).height(),
			left: $(this).offset().left - $("#all").offset().left });
			$(this).blur();
			var zip = $("form.change-location input[name=zipcode]");
			$(zip).focus();
	});
	$("body").click(function() { $("#change-zip-dialog").fadeOut('fast'); });
	$("#change-zip-dialog").click(function(e) { e.stopPropagation(); });
	$(document).keypress(function(e) { if (e.keyCode == 27) { $("#change-zip-dialog").fadeOut('fast'); }});


	/* post comment */
	$("#post-comment").click( function(){
		var form = $("#commentForm");
		var post = $(form).serialize();
		$.post($(form).attr('action'),post, function(data){
			if(data.response != 'Success'){
				//alert(data.response);
				var site_url = 'http://'+window.location.hostname+'/service_shop/detail?branch_id='+$('input#remoteid',$('#commentForm')).val()+'&tab=reviews';
				$.ubox('/user/login?url='+escape(site_url));
			}else{
				
				$.post('/ratings/rate/', $("input#content_type, input#remoteid, input#userid, input#rating ", $('#commentForm')).serialize(), function( data ) {
					if (data.response != 'Success') {
						alert(data.response);
					} else {
						//location.reload(true);
						//console.log(data.rating + ' ' + data.rating_count);
						$.post('/ssmd/update_shop_rating/','shop_id='+$('input#remoteid').val()+'&rating_count='+data.rating_count+'&rating_avg='+data.rating,function() { 
							if (data.response != 'Success')
							{
								alert(data.response);
							} else {
								location.reload();
							}
						});
						return false;
					}
				}, "json");
				
				//location.reload(true);
			}
		},"json"); 
	});

	/* garage */
	var arrow = $('#vehicle span.arrow');
	var closeVehicleSelection = function(){ 
		$(arrow).attr('id','close');
		$("#overlay").hide(); 
		$("#garage-year option:eq(0)").attr({selected:"selected"});
		$('#garage-make').html('<option value="">Select Make</option>').attr('disabled','disabled');
		$('#garage-model').html('<option value="">Select Model</option>').attr('disabled','disabled');
		$('#garage-submodel').html('<option value="">Select Submodel</option>').attr('disabled','disabled');
		$('#garage-engine').html('<option value="">Select Engine</option>').attr('disabled','disabled');
		$("#vehicle-select").slideUp('fast');
		return false;  
	};
 	
	$('.blockOverlay').live("click", function(){closeVehicleSelection()});
	$('a.name').unbind('click').click(function(e){
		arrow.css({zIndex:'10000'});    
		if($(arrow).attr('id') == 'close'){
			var URL = document.location.href; 			
			//var str1 = /vad/
			var str2 = /key/; 
			var str3 = /body_area/; 
						
			if(URL != undefined){ 				
				//var matchPos1 = URL.search(str1);			 
				//if(matchPos1 != -1){ /* In VAD */ 
					var matchPos2 = URL.search(str2);	 			
					var matchPos3 = URL.search(str3); 				
					if(matchPos2 != -1 || matchPos3 != -1){/* diagnose start */													
						if($("#diagnose-message").length == 0){
							$("#vehicle-select .vs-heading").after("<div class='yellow-box' id='diagnose-message' style='margin:5px'>Take note: Changing your vehicle will re-start the diagnosis process</div>"); 
						}	
						$("input[name=redirect_to]").val("/vad/diagnose"); 					
						
					}
				//}
			} 
			var x = $("#all").offset().left + 10; 
			var y = $("#all").offset().top + 126;  	
			var html = 	$("#vehicle-select").html;	   
			$("#overlay").show(); 
			$("#vehicle-select").slideDown('fast').css({zIndex:2000,top: y+'px',right: x+'px'});    						
			//$.blockUI({ message: '<div id="mygarage"></div>' }); 
			$(arrow).attr('id','open');    
			//$("#vehicle-select").slideDown('fast').css({zIndex:2000,top: y+'px',right: x+'px'});    			
		}else{    
			closeVehicleSelection();   
		}    
	});  
	$("form.change-vehicle").submit( function(){	
		
		var URL = document.location.href; 			
		var URL = document.location.href; 			
		var str = "estimate_costs/detail";
		if(URL.match(str) != null){
			var ischange = confirm("Choosing another vehicle will remove all jobs in your current list. \n Continue?"); 
			var redirect = $("input[name=redirect_to]"); 
			if(ischange){
				$(redirect).val('/estimate_costs'); 
			}else{
				closeVehicleSelection(); 
				return false; 
			}	
		} 
		if($(this).attr('id') == 'garage-carpicker'){
		if($('#garage-year').val() == ''){ 
			alert("Please select year, make, model, submodel and engine to continue.");
			return false;
		} 
		if($('#garage-make').val() == '' ||  $('#garage-make').val() == undefined){
			alert("Please select make, model, submodel and engine to continue.");
			return false;	
		}		
		if($('#garage-model').val() == '' ||  $('#garage-model').val() == undefined){
			alert("Please select model, submodel and engine to continue...");  
			return false; 
		} 
		if($('#garage-submodel').val() == '' ||  $('#garage-submodel').val() == undefined){
			alert("Please select submodel and engine to continue...");  
			return false; 
		}
		if($('#garage-engine').val() == '' ||  $('#garage-engine').val() == undefined){
			alert("Please select engine to continue...");  
			return false; 
		}
		}
		return true;      
	});        
	
	$("input.zip").keypress(function (e){ 
			var x = $(this).val();
			if( e.which!=8 && e.which!=13 && e.which!=0 && (e.which<48 || e.which>57)){return false; $(this).focus();}
			if(x.length == 5  && e.which!=8 && e.which!=0 && e.which!=13){ return false;$(this).focus();}  									 			
	});    	
	 
	$("#btn-search").click(function(){		
		if($.trim($("#search_main").val()).length <= 0 || $("#search_main").val() == 'Search ...'){
			return false; 
		}
	});  

	
		
	$("a.btn-login").unbind('click').click(function() { 
		ubox_url = $(this).attr('rel');
		if ($.ubox)
		{
			$.ubox(ubox_url);
		}
	});
	
	$("a.btn-register").unbind('click').click(function() { 
		ubox_url = $(this).attr('rel');
		if ($.ubox)
		{
			$.ubox(ubox_url);
		}
	});
	
	$("a.btn-add-vehicle").unbind('click').click(function() { 
		ubox_url = $(this).attr('rel');
		if ($.ubox)
		{
			$.ubox(ubox_url);
		}
	});
	
	var tip_holder = $("span.tooltip"); 		
	$(".tooltip-complexity").hover( function(){		
		$(tip_holder).css({
			top:  $(this).offset().top  - $("#all").offset().top + $(this).height(),
			left: $(this).offset().left - ($("#all").offset().left + 150) }).show();      	
		
	},function(){
		$(tip_holder).hide(); 
	});
	
	/** auto popup login on restricted page */
	function auto_trigger_login()
	{
		var address = window.location.href;
		var site_url = "http://"+window.location.hostname;
		var trigger_login = /popup=login/.test(address);
		var urlkey = /restricted(?:=([^&]*))?/g;
		var url_redirect = address.match(urlkey);
		if ($("a.btn-login").length > 0) 
		{
			if (url_redirect && $.ubox && !$("#username").length)
			{
				var ubox_url = $("a.btn-login").attr('rel'); 
				var restricted = url_redirect.toString().split("=");
				$.ubox(ubox_url+restricted[1]);
			}
		}
	}
	auto_trigger_login();
});
 
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


/* validate email address */
function validate_email(email){
	var regemail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var regurl = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
	if(regemail.test(email) == false && email.length>0){
		return false;
	}
	return true;
}
/* javascript in_array */
function in_array(needle, haystack, argStrict) {
	var key = '', strict = !!argStrict;
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	} 
	return false;
}
 
function sclinkCode(rsid, linkName, event, evar, prop, evarV) 
{
    var s=s_gi(rsid);
    s.linkTrackVars='';
    s.linkTrackEvents='';

    if (typeof(evar) != "undefined" && evar != null) {
    	for (i in evar) { 
    		   s[i] = evar[i];
    		   if (s.linkTrackVars != '') {
    	    		s.linkTrackVars += ',';
    	    	}
    		   s.linkTrackVars+=i;
    	};
    }

    if (typeof(prop) != "undefined" && prop != null) {
    	for (i in prop) { 
    		   s[i] = prop[i];
    		   if (s.linkTrackVars != '') {
    	    		s.linkTrackVars += ',';
    	    	}
    		   s.linkTrackVars+=i;
    	};
    }

    if (typeof(event) != "undefined" && event != null) {
    	if (s.linkTrackVars != '') {
    		s.linkTrackVars += ',';
    	}
    	s.linkTrackVars   += 'events';
    	for (i=0; i < event.length; i++) { 
    		   if (s.linkTrackEvents != '') {
    	    		s.linkTrackEvents += ',';
    	    		s.events += ',';
    	    	}
    		   s.linkTrackEvents = event[i];
    	       s.events          = event[i];
    	};
    }

    if (s.linkTrackVars == '') { 
    	s.linkTrackVars = 'None';
    }
    if (s.linkTrackEvents == '') {
    	s.linkTrackEvents = 'None';
    }
    
    s.tl(true,'o',linkName);
    //salert(rsid+"\n"+s.linkTrackEvents+"\n"+s.linkTrackVars);    
} 

function schandleOnclickEvent(s_account, url, event, evar, prop, desc, evarV, propV)
{
	var scevar          = null;
	var scevent         = null;
	var scprop          = null;

	if (typeof(event) != "undefined" && event != null) {
		scevent      = [];
		scevent[0]   =  event;
	}
    if (typeof(evar) != "undefined" && evar != null) {
        scevar   = [];
        if (typeof(evarV) != "undefined" && evarV != null) {
        	scevar[evar] = evarV;
        } else {
        	scevar[evar] = event;
        }
    }
    if (typeof(prop) != "undefined" && prop != null) {
        scprop   = [];
        if (typeof(propV) != "undefined" && propV != null) {
        	scevar[prop] = propV;
        } else {
        	scprop[prop] = event;
        }
    }
    sclinkCode(s_account, desc, scevent, scevar, scprop);
    window.location=url;
}

Array.prototype.indexOf = function(k){
	var len = this.length;
	for(i=0;i<len;i++){
	  if(this[i] == k){
	    return i;
	  }
	}
	return -1;
}