// dtd
    var oldDiv = '';
    var oldHeight = '';
/////
    /* No results Request a Deal */
    var dadErr=0;
    jQuery(document).ready(function() {
    	
    	jQuery('#write_in_name').click(function(){
    		if(jQuery('#write_in_name').val() == ' Busniess Name' || jQuery('#write_in_name').val() ==' Busniess Name Required'){
    			jQuery(this).val('');
    		}else{     			
    			return false;
    		}    		    		
    	});
    	jQuery('#write_in_name').blur(function(){
    		if(jQuery('#write_in_name').val() == ''){
    			jQuery('#write_in_name').val(' Busniess Name');
    		}else{
    			return false;
    		}
    	}); 	
    	
    	jQuery('#write_in_location').click(function(){
    		if(jQuery('#write_in_location').val() == ' City and State of Business' || jQuery('#write_in_location').val() ==' City and State of Business Required'){
    			jQuery(this).val('');
    		}else{     			
    			return false;
    		}    		    		
    	});
    	jQuery('#write_in_location').blur(function(){
    		if(jQuery('#write_in_location').val() == ''){
    			jQuery('#write_in_location').val(' City and State of Business');
    		}else{
    			return false;
    		}
    	});     	

    	jQuery('#dad_email').click(function(){
    		if(jQuery('#dad_email').val() == ' Your Email' || jQuery('#dad_email').val() ==' Your Email Required'){
    			jQuery(this).val('');
    		}else{     			
    			return false;
    		}    		    		
    	});
    	jQuery('#dad_email').blur(function(){
    		if(jQuery('#dad_email').val() == ''){
    			jQuery('#dad_email').val(' Your Email');
    		}else{
    			return false;
    		}
    	});   
    	
    	jQuery('#dad_cell').click(function(){
    		if(jQuery('#dad_cell').val() == ' Ten digit cell phone for SMS updates (optional)'){
    			jQuery(this).val('');
    		}else{     			
    			return false;
    		}    		    		
    	});
    	jQuery('#dad_cell').blur(function(){
    		if(jQuery('#dad_cell').val() == ''){
    			jQuery('#dad_cell').val(' Ten digit cell phone for SMS updates (optional)');
    		}else{
    			return false;
    		}
    	});      
    	jQuery('#dad_comments').click(function(){
    		if(jQuery('#dad_comments').val() == 'Additional Feedback'){
    			jQuery(this).val('');
    		}else{     			
    			return false;
    		}    		    		
    	});
    	jQuery('#dad_comments').blur(function(){
    		if(jQuery('#dad_comments').val() == ''){
    			jQuery('#dad_comments').val('Additional Feedback');
    		}else{
    			return false;
    		}
    	});   	    	
    	
		jQuery('#dad-results-submit').click(function(){				
			if(jQuery('#write_in_name').val() == '' || jQuery('#write_in_name').val() == ' Busniess Name' || jQuery('#write_in_name').val() ==' Busniess Name Required'){
				jQuery('#write_in_name').css({'border':'1px solid #f00','color':'#f00','background':'#fff3f3'}).val(' Busniess Name Required').focus();
				
				return false;
			}else{				
				jQuery('#write_in_name').css({'border':'1px solid #bbbfc1','color':'#bbbfc1','background':'#fff'});				
				}				
			if(jQuery('#write_in_location').val() == '' || jQuery('#write_in_location').val() == ' City and State of Business' || jQuery('#write_in_location').val() ==' City and State of Business Required'){
				jQuery('#write_in_location').css({'border':'1px solid #f00','color':'#f00','background':'#fff3f3'}).val(' City and State of Business Required').focus();
				
				return false;
			}else{
				jQuery('#write_in_location').css({'border':'1px solid #bbbfc1','color':'#bbbfc1','background':'#fff'});	
				}				
			if(jQuery('#dad_email').val() == '' || jQuery('#dad_email').val() == ' Your Email' || jQuery('#dad_email').val() ==' Your Email Required'){
				jQuery('#dad_email').css({'border':'1px solid #f00','color':'#f00','background':'#fff3f3'}).val(' Your Email Required').focus();
				
				return false;
			}else{
				jQuery('#dad_email').css({'border':'1px solid #bbbfc1','color':'#bbbfc1','background':'#fff'});
			}
			
			if(!isValidEmailAddress(jQuery('#dad_email').val())){
				jQuery('#dad_email').css({'border':'1px solid #f00','color':'#f00','background':'#fff3f3'}).val(' Valid Email Required').focus();
				return false;
			}else{
				jQuery('#dad_email').css({'border':'1px solid #bbbfc1','color':'#bbbfc1','background':'#fff'});
			}
			
		if(dadErr==1){
			
			return false;
		}else{
			if(jQuery('#dad_cell').val()==' Ten digit cell phone for SMS updates (optional)'){
				jQuery('#dad_cell').val('');
			}			
			
			if(jQuery('#dad_comments').val()=='Additional Feedback'){
				jQuery('#dad_comments').val();
			}
			// submit form
			
			jQuery.post("/demandadeal/index/ajaxPost/", {write_in_name:jQuery('#write_in_name').val(),write_in_location:jQuery('#write_in_location').val(),dad_email: jQuery('#dad_email').val(),dad_cell:jQuery('#dad_cell').val(), dad_comments:jQuery('#dad_comments').val()},function(data){
				jQuery('#no-result-success').html('Thank you, we will notify you when we receive your deal');
                setTimeout(function(){
                    jQuery('#no-result-success').html('');
                },2000);
			} );
			
        }
        });


        /****  header login javascript ****/
        jQuery('#login-link').click(function(){
            jQuery('#head-login-wrap').fadeIn("slow");
        });

        jQuery('#close-login').click(function(){
            jQuery('#head-login-wrap').fadeOut("slow");
        })

        /**** Login logic from the header login ****/
        jQuery('#head-login-submit').live("click",function(e){
        	jQuery('#head-login-submit').html('<img src="/skin/frontend/default/citydeals/images/ajax-loader.gif"/>');
            jQuery('#head-login-submit').css('background-color','#fff');
            var password = encode64(jQuery('#head-login-password-field').val());            
            jQuery.ajax({
                url: '/discussthedeal/index/login',
                data: {"user":jQuery('#head-login-username-field').val(),"pass":password},
                dataType: 'json',
                success: function(data) {                	           
                    if(data){                    	
                        if(data.success == true)
                        {   
                        	
                        	// If load is successful then move cart header
                        	jQuery('.header-top-container').load('/ #header-top',function(response, status, xhr){
                                if(status == "success")
                                {
                                    jQuery('#header-cart').css('right','-395px');
                                }
                            });
                        }  
                        else {
                            // Error handling
                            jQuery('#head-login-error-wrap').show();
                            jQuery('#head-error-message').html(data.msg);
                            // Logic for countdown
                            var headError=5;
                            jQuery('#head-error-footer-number').html(headError);

                            var intervalId;
                            intervalId = setInterval(function(){
                                if(headError == 0)
                                {
                                    clearInterval(intervalId);
                                    jQuery('#head-login-error-wrap').fadeOut("slow");
                                }
                                else
                                {
                                    headError--;
                                    jQuery('#head-error-footer-number').html(headError);
                                }
                            },1000);

                            jQuery('#head-login-submit').html('Login');
                            jQuery('#head-login-submit').css('background-color','#9dd0dd');
                        } // End if else successful login                        
                    }
                    else { // if data response is null
                    // Error handling
                    jQuery('#head-login-error-wrap').show();
                    jQuery('#head-error-message').html("Unable to login, please go to Checkout to login");
                    // Logic for countdown
                    var headError=5;
                    jQuery('#head-error-footer-number').html(headError);

                    var intervalId;
                    intervalId = setInterval(function(){
                        if(headError == 0)
                        {
                            clearInterval(intervalId);
                            jQuery('#head-login-error-wrap').fadeOut("slow");
                        }
                        else
                        {
                            headError--;
                            jQuery('#head-error-footer-number').html(headError);
                        }
                    },1000);

                    jQuery('#head-login-submit').html('Login');
                    jQuery('#head-login-submit').css('background-color','#9dd0dd');
                } // End if else data is null                    
                },
                error: function(data) {                          
                    jQuery('#head-login-error-wrap').show();
                    jQuery('#head-error-message').html("There was a problem processing your request."); 
                }
            });
        e.preventDefault();
        });
    
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + "=";
    function encode64(input) {
         input = escape(input);
         var output = "";
         var chr1, chr2, chr3 = "";
         var enc1, enc2, enc3, enc4 = "";
         var i = 0;

         do {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
               enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
               enc4 = 64;
            }

            output = output +
               keyStr.charAt(enc1) +
               keyStr.charAt(enc2) +
               keyStr.charAt(enc3) +
               keyStr.charAt(enc4);
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
         } while (i < input.length);

         return output;
      }

        /***************************************/
        /******** Email Signup / Login *********/
        /***************************************/

            // This sets the value in the password field
        jQuery('#email-lightbox-login-username').live('keyup',function(){
             jQuery('#email-lightbox-login-username').val(jQuery(this).val());
        });

            // This sets the value in the password field
        jQuery('#email-lightbox-login-password').live('keyup',function(){
             jQuery('#email-lightbox-login-password').val(jQuery(this).val());
        });

            // This sets the value in the password field
        jQuery('#email-lightbox-landing-email').live('keyup',function(){
             jQuery('#email-lightbox-landing-email').val(jQuery(this).val());
        });

            // This sets the value in the password field
        jQuery('#email-lightbox-landing-zip').live('keyup',function(){
             jQuery('#email-lightbox-landing-zip').val(jQuery(this).val());
        });

            // This sets the value in the password field
        jQuery('#email-lightbox-landing-referral').live('keyup',function(){
             jQuery('#email-lightbox-landing-referral').val(jQuery(this).val());
        });

        // Handles the switching of the password fields
        jQuery('.email-lightbox-input').live("focus",function(e){
            if(jQuery(this).val() == "Email Address" || jQuery(this).val() == "Zip Code" || jQuery(this).val() == "Referral Code"){
                jQuery(this).val('');
                if(jQuery(this).attr('id') == 'email-lightbox-login-password-fake'){
                    jQuery(this).hide();
                    jQuery(this).parent().children('#email-lightbox-login-password').show();
                    jQuery(this).parent().children('#email-lightbox-login-password').focus();
                }
            }else if(jQuery(this).attr('id') == 'email-lightbox-login-password-fake'){
                jQuery(this).hide();
                jQuery(this).parent().children('#email-lightbox-login-password').show();
                jQuery(this).parent().children('#email-lightbox-login-password').focus();
            }
            else if(jQuery(this).attr("id")== "email-lightbox-login-password-fake"){
                    jQuery(this).hide();
                    jQuery(this).parent().children('#email-lightbox-login-password').show();
                    jQuery(this).parent().children('#email-lightbox-login-password').css('color','#393939');
                    jQuery(this).parent().children('#email-lightbox-login-password').focus();
            }
            jQuery(this).css('color','#393939');
        });

            // Handles the values of the fields when user leaves...reset original values
        jQuery('.email-lightbox-input').live("blur",function(e){
            if(jQuery(this).val()== ''){
                if(jQuery(this).attr('id')=='email-lightbox-landing-zip'){
                    jQuery(this).val('Zip Code');
                }else if(jQuery(this).attr('id')== 'email-lightbox-login-password'){
                    jQuery(this).hide();
                    jQuery(this).parent().children('#email-lightbox-login-password-fake').show();
                    jQuery(this).parent().children('#email-lightbox-login-password-fake').val('Password');
                }else if(jQuery(this).attr('id')== 'email-lightbox-landing-referral'){
                    jQuery(this).val('Referral Code');
                }else{
                    jQuery(this).val('Email Address');
                }

                jQuery(this).css('color','#bbbfc1');
                jQuery(this).parent().children('#email-lightbox-login-password-fake').css('color','#bbbfc1');
            }
            jQuery(this).parent().children('#email-lightbox-login-error-message').html('');
            jQuery(this).parent().children('#email-lightbox-landing-error-message').html('');
        });

        jQuery('#lightbox-forgot-password').live("click",function(e){
            jQuery.cookie("lbtrue",true);
        });

        jQuery('#email-lightbox-landing-cpc-button').live("click",function(e){

                // Alter button
            jQuery(this).css('background-color','white');
            var $this = jQuery(this);

            // create cookie so lightbox doesn't come back';
            jQuery.cookie("lbtrue",true);

            if(jQuery('#email-lightbox-landing-email').val()!= 'Email Address' && jQuery('#email-lightbox-landing-zip').val()!= 'Zip Code')
            {
                    // Email is not valid
                if(!isValidEmailAddress(jQuery(this).parent().children('#email-lightbox-landing-email').val())){
                    jQuery(this).parent().children('#email-lightbox-landing-error-message').html('** A Valid Email is Required! **');
                    $this.parents().find('#email-lightbox-landing-cpc-button').css('background-image','');
                    $this.parents().find('#email-lightbox-landing-cpc-button').val('Submit');
                    $this.parents().find('#email-lightbox-landing-cpc-button').css('background-color','#84c4d4');

                }else{ // Email is valid check zipcode
                        // Check to see if zip is invalid
                    if(!isValidUSZip(jQuery('#email-lightbox-landing-zip').val())){
                        jQuery(this).parent().children('#email-lightbox-landing-error-message').html('** A Valid Zip is Required **');
                        $this.parents().find('#email-lightbox-landing-cpc-button').css('background-image','');
                        $this.parents().find('#email-lightbox-landing-cpc-button').val('Submit');
                        $this.parents().find('#email-lightbox-landing-cpc-button').css('background-color','#84c4d4');
                    }else{  // Zip is valid submit form
                        // create cookie so lightbox doesn't come back';
                        jQuery.cookie("lbtrue",true);

                        jQuery.post('newsletter/subscriber/newemail',{"email":jQuery('#email-lightbox-landing-email').val(),"zipcode":jQuery('#email-lightbox-landing-zip').val(),"referral":jQuery('#email-lightbox-landing-referral').val()}, function(data){
                            $this.parents().find('#email-lightbox-landing-cpc-button').hide();
                            $this.parents().find('#email-lightbox-body-left-thankyou-header').show();
                            $this.parents().find('#email-lightbox-body-left-thankyou-content').show();
                            if(jQuery('#email-lightbox-landing-referral').val() != 'Referral Code'){
                                $this.parents().find('#email-lightbox-landing-site-button-ref').show();
                            }else{
                                $this.parents().find('#email-lightbox-landing-site-button').show();
                            }
                        });
                            // Get zone information and set cookies from zip_code
                        jQuery.ajax({
                            url: '/location/search/zipServices',
                            data: {"zip":jQuery('#email-lightbox-landing-zip').val()},
                            dataType: 'json',

                            success: function(data) {
                                if(data != false){
                                    jQuery.cookie('index_state_pre',data.state_prefix,{expires: 7, path: '/'});
                                    jQuery.cookie('index_zip', data.zip_code,{expires: 60, path: '/'});
                                    jQuery.cookie('index_zone', data.zone,{expires: 7, path: '/'});
                                    jQuery.cookie('user_zone', data.city+', '+data.state_prefix,{expires: 7, path: '/'});
                                }
                                jQuery.cookie('pixel', 'fire',{expires:7, path: '/'});
                            },
                            error: function(data) { }
                        });
                    }
                }
            }else{ // Error handling if both fields are blank
                jQuery(this).parent().children('#email-lightbox-landing-error-message').html('** A Valid Email and Zip are Required if Submitted **');
                    $this.parents().find('#email-lightbox-landing-cpc-button').css('background-image','');
                    $this.parents().find('#email-lightbox-landing-cpc-button').val('Submit');
                    $this.parents().find('#email-lightbox-landing-cpc-button').css('background-color','#84c4d4');
            }
        });
        
            // Handles the submittion of the login
        jQuery('#email-lightbox-login-button').live("click",function(e){

            var $this = '';
            jQuery(this).css('background-color','white');
            $this = jQuery(this);  // To be used inside of post function

            // create cookie so lightbox doesn't come back';
            jQuery.cookie("lbtrue",true);

                // Initial check that the user actually filled in the form fields
            if(jQuery('#email-lightbox-login-username').val()!= 'Email Address' && jQuery('#email-lightbox-login-password').val()!= '')
            {
                if(!isValidEmailAddress(jQuery('#email-lightbox-login-username').val())){
                    jQuery(this).parent().children('#email-lightbox-login-error-message').html('** A Valid Email is Required! **');
                    $this.parents().find('#email-lightbox-login-button').css('background-image','');
                    $this.parents().find('#email-lightbox-login-button').val('Submit');
                    $this.parents().find('#email-lightbox-login-button').css('background-color','#84c4d4');

                }else{
                    // Base64Encode password
                    var password = encode64( jQuery('#email-lightbox-login-password').val() );
                    jQuery.post('/discussthedeal/index/login', {"user":jQuery('#email-lightbox-login-username').val(),"pass":password}, function(data){
                        var data = jQuery.parseJSON(data);
                        if(data.success == true)
                        {   // If load is successful then move cart header
                                // Needs to close three times
                            jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');
                                // reload header
                            jQuery('.header-top-container').load('/ #header-top',function(response, status, xhr){
                                if(status == "success")
                                {
                                    jQuery('#header-cart').css('right','-395px');

                                }
                            });
                            // Create cookie to prevent box from popping back up
                            jQuery.cookie("lbtrue", true);

                        }
                        else
                        {       // show login error
                            $this.parents().children('#footer-login-error-wrap').show();
                            $this.parents().find('#footer-error-message').html(data.msg);
                            // Logic for countdown
                            var headError=5;
                            $this.parents().find('#footer-error-footer-number').html(headError);

                            var intervalId;
                            intervalId = setInterval(function(){
                                if(headError == 0)
                                {
                                    clearInterval(intervalId);
                                    $this.parents().children('#footer-login-error-wrap').fadeOut("slow");
                                }
                                else
                                {
                                    headError--;
                                    $this.parents().find('#footer-error-footer-number').html(headError);
                                }
                            },1000);
                                // Repair button
                            $this.parents().find('#email-lightbox-login-button').css('background-image','');
                            $this.parents().find('#email-lightbox-login-button').val('Log In');
                            $this.parents().find('#email-lightbox-login-button').css('background-color','#84c4d4');
                        }   // End error handling
                    });
                }

             }else{ // Error handling if both fields are blank
                jQuery(this).parent().children('#email-lightbox-login-error-message').html('** A Valid Email and Password are Required if Submitted **');
                $this.parents().find('#email-lightbox-login-button').css('background-image','');
                $this.parents().find('#email-lightbox-login-button').val('Log In');
                $this.parents().find('#email-lightbox-login-button').css('background-color','#84c4d4');
            }
       });

        jQuery('#email-lightbox-landing-site-button').live("click",function(e){
            jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');
            jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');

            // create cookie so lightbox doesn't come back';
            jQuery.cookie("lbtrue",true);
        });
        jQuery('#email-lightbox-landing-site-button-ref').live("click",function(e){
            jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');
            jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');jQuery(document).trigger('close.hardybox');

            // create cookie so lightbox doesn't come back';
            jQuery.cookie("lbtrue",true);
        });

	}); 
		
    /* End no results Request a Deal */   
    
/*
 *ticker
 */
<!--
	/*
        jQuery(document).ready(function() {

		jQuery.ajax({
	    type: "POST",
	    url: "/citydeals/index",
	    data: "{}",
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",
	    success: function(data) {
	      //alert(data.digits.OneMillion);
	      jQuery('#ticker-ten-million').html(data.digits.TenMillion);
	      jQuery('#ticker-one-million').html(data.digits.OneMillion);
	      jQuery('#ticker-hundred-thousand').html(data.digits.HundredThousand);
	      jQuery('#ticker-ten-thousand').html(data.digits.TenThousand);
	      jQuery('#ticker-one-thousand').html(data.digits.OneThousand);
	      jQuery('#ticker-one-hundred').html(data.digits.OneHundred);
	      jQuery('#ticker-ten').html(data.digits.Ten);
	      jQuery('#ticker-one').html(data.digits.One);
	    }
	  });

	});

        function updateTicker(){
        	jQuery.ajax({
                type: "POST",
                url: "/citydeals/index",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                  jQuery('#ticker-ten-million').html(data.digits.TenMillion);
                  jQuery('#ticker-one-million').html(data.digits.OneMillion);
                  jQuery('#ticker-hundred-thousand').html(data.digits.HundredThousand);
                  jQuery('#ticker-ten-thousand').html(data.digits.TenThousand);
                  jQuery('#ticker-one-thousand').html(data.digits.OneThousand);
                  jQuery('#ticker-one-hundred').html(data.digits.OneHundred);
                  jQuery('#ticker-ten').html(data.digits.Ten);
                  //jQuery('#ticker-one').html(digit);
                 jQuery('#ticker-one').html(data.digits.One);
                }
	  });
        }
*/

//-->

/* main_top js */

    var containerWidth= 0;
    jQuery(document).ready(function(){

        /*
         * Email subscription
         */
        jQuery('.form-go').live('click',function(){
            if(isValidEmailAddress(jQuery('#input-email').val())){
                jQuery('#customer-zip-code').hide();
                jQuery('#deal-zone').fadeIn('slow');
                jQuery('#sub-zip-code').fadeIn('slow');
            }else{
                jQuery('#input-email-msg').fadeIn('slow');
                jQuery('#input-email-msg').html('Please Enter a Valid Email')
                setTimeout(function(){
                    jQuery('#input-email-msg').fadeOut('slow');
                },2000);
            }
        });
        jQuery('#ftk-email').focus(function(){
           if( jQuery(this).val()=='  Enter email for deal updates'){
                jQuery(this).val('');
            }else{
                return false;
            }
        });
        jQuery('#ftk-email').blur(function(){
           if(jQuery(this).val()==''){
               jQuery(this).val('  Enter email for deal updates');
           }else{
               return false;
           }
        });
        jQuery('#sub-zipcode').click(function(){
           if(jQuery(this).val()=='Enter your zip code'){
               jQuery(this).val('');
           }else{
               return false;
           }
        });
        jQuery('#sub-zipcode').blur(function(){
           if(jQuery(this).val()==''){
               jQuery(this).val('Enter your zip code');
           }else{
               return false;
           }
        });
        jQuery('#ftk-cell').click(function(){
           if(jQuery(this).val()=='  10 Digit Cell Phone (optional)'){
               jQuery(this).val('');
           }else{
               return false;
           }
        });
        jQuery('#ftk-cell').blur(function(){
           if(jQuery(this).val()==''){
               jQuery(this).val('  10 Digit Cell Phone (optional)');
           }else{
               return false;
           }
        });
        jQuery('#ftk-btn').live('click',function(){
            if(isValidEmailAddress(jQuery('#ftk-email').val())){
             jQuery('#deal-zone').fadeIn('slow');
             jQuery('#deal-zone').css({'height':jQuery(document).height()});
             jQuery('#sub-zip-code').css({'top':jQuery(document).height()/2});
             jQuery('#customer-zip-code').hide();
             jQuery('#sub-zip-code').fadeIn('slow');
             jQuery('#input-email').val(jQuery('#ftk-email').val());
             if(jQuery('#ftk-email').val()!='  10 Digit cell phone (optional)'){
                 jQuery('#hidden-cell').val(jQuery('#ftk-cell').val());
             }
            }else{
                jQuery('#ftk-email-msg').fadeIn('slow');
                jQuery('#ftk-email-msg').html('Please Enter a Valid Email')
                setTimeout(function(){
                    jQuery('#ftk-email-msg').fadeOut('slow');
                },2000);
                jQuery('#ftk-email').focus();                
            }
        });
        jQuery('.sub-zip-btn').live('click',function(){
              jQuery.ajax({
                        url: '/location/search/zipServices',
                        data: {"zip":jQuery('#sub-zipcode').val()},
                        dataType: 'json',
                        success: function(data) {
                           if(data != false){
                                jQuery('#hidden-zip').val(data.zip_code);                                
                                jQuery('#sign-up').submit();
                                jQuery('#deal-zone').fadeOut('slow');
                                jQuery('#sub-zip-code').fadeOut('slow');
                            }else{
                                jQuery('#sub-zip-msg').html('Please enter a valid zip code');
                                jQuery('#sub-zip-msg').fadeIn('slow');
                                setTimeout(function(){
                                    jQuery('#sub-zip-msg').fadeOut('slow');
                                },2000);
                            }
                        },
                        error: function(data) {
                            jQuery('#sub-zip-msg').html('There was and error processing your request');
                            jQuery('#sub-zip-msg').fadeIn('slow');
                            setTimeout(function(){
                                jQuery('#sub-zip-msg').fadeOut('slow');
                            },2000);
                        }
                });

        });

       /*
       jQuery('#keyword').keyup(function(){
           jQuery('#search-auto-fill').fadeOut();
           if(jQuery(this).val().length >=3){
               jQuery('#keyword-auto-fill').html('<img src="/skin/frontend/default/citydeals/hardybox/images/loading.gif">');
              jQuery('#keyword-auto-fill').stop().load('/keyword?keyword='+escape(jQuery('#keyword').val())+' #auto-fill',function(html){
              tmp = jQuery(html).find('#auto-fill').html();
              jQuery('#keyword-auto-fill').html(header-shatmp);
              jQuery('#keyword-auto-fill').fadeIn();
                $val = jQuery('#keyword-auto-fill>ul>li');
                $val.each(function(){
                    $val.click(function(){
                        $li = jQuery(this);
                        jQuery('#keyword').val($li.html());
                        jQuery('#keyword-auto-fill').hide();
                    });
                });
             });
           }
       });
       */
       jQuery('#keyword').change(function(){
           jQuery('#keyword-auto-fill').fadeOut();
           jQuery('#search-auto-fill').fadeOut();
       });
       /*
        jQuery('#customer_location').keyup(function(){
            jQuery('#keyword-auto-fill').fadeOut();
           if(jQuery(this).val().length >=4){
               jQuery('#search-auto-fill').html('<img src="/skin/frontend/default/citydeals/hardybox/images/loading.gif">');
              jQuery('#search-auto-fill').stop().load('/geo?city='+escape(jQuery('#customer_location').val())+' #auto-fill',function(html){
              tmp = jQuery(html).find('#auto-fill').html();
              jQuery('#search-auto-fill').html(tmp);
              jQuery('#search-auto-fill').fadeIn();
                $val = jQuery('#search-auto-fill>ul>li');
                $val.each(function(){
                    $val.click(function(){
                        $li = jQuery(this);
                        jQuery('#customer_location').val($li.html());
                        jQuery('#search-auto-fill').hide();
                    });
                });
             });
           }
       });
       */
       jQuery('#customer_location').change(function(){
           jQuery('#search-auto-fill').fadeOut();
           jQuery('#keyword-auto-fill').fadeOut();
       });
       jQuery('a.home-page-category[rel*=more-cat]').live('click',function(){
           containerWidth=0;
           jQuery('#more-cat').toggle();
           jQuery('#more-cat').css({'position':'absolute'});
           jQuery('#more-cat').css({'top':jQuery('#all-cats').offset().bottom+1});
           jQuery('#more-cat').css({'left':jQuery('.middle-container').offset().left+4});

           jQuery('#cat-menu').css({'position':'absolute'});
           jQuery('ul.top-cat').each(function(){
             containerWidth += parseInt(jQuery(this).width()+12);
              jQuery('#more-cat').css({'width':containerWidth});                      
           })
           return false;
       })
        jQuery('#wrapper').click(function(){
           jQuery('#more-cat').fadeOut();
           return false;
        });
        
        jQuery('#cat-menu').live('click',function(){
            jQuery(this).find('a:first').trigger('click');
        })
    });

/*
*  email validation
*/
 function isValidEmailAddress(emailAddress) {
 		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 		return pattern.test(emailAddress);
	}

function isValidUSZip(sZip) {
    var pattern = new RegExp(/^\d{5}(-\d{4})?$/)
   return pattern.test(sZip);
}

/*
 * Citydeals Tabs
 */

jQuery(document).ready(function () {
		var tabContainers = jQuery('div.cdtabs > div');
		tabContainers.hide().filter(':first').show();

		jQuery('div.cdtabs ul.tabNavigation a').click(function () {
				tabContainers.hide();
				tabContainers.filter(this.hash).show();
				jQuery('div.cdtabs ul.tabNavigation a').removeClass('selected');
				jQuery(this).addClass('selected');
				return false;
		}).filter(':first').click();

            jQuery('a.activator[rel=hardybox]').hardybox(
            {opacity:.7,draggable:false,targetDiv:'#p_container'});
            jQuery('a.activator[rel=cart]').hardybox(
            {opacity:.7,draggable:false,targetDiv:'#p_container'});
    });


/*
 * Location Ratings
 */

function showRatingHover(showHover, ratingValue, locationId)
{
    if (locationId) {
        ratingElem = jQuery('#rating-fill-hover-' + locationId);
    }
    else {
        ratingElem = jQuery('.rating-fill-hover');
    }

	if (showHover) {
		var fiveStarsWidth = 80;
		ratingElem.css('z-index', 5)
                  .css('display', 'block')
                  .css('width', (fiveStarsWidth * (ratingValue/5)) + 'px');
	} else {
		ratingElem.css('z-index', 0)
		          .css('display', 'none');
	}
}

function rateLocation(locationId, ratingValue)
{
	var data = {'location_id' : locationId,
				'rating' : ratingValue
	};

    var ratingMessagesElem = jQuery('#rating-messages-' + locationId);

	// Submit form
	jQuery.ajax({
		type: "POST",
		url: "/locationrating/index/rate/",
		data: data,
		dataType: "json",
		success: function(data) {
			ratingMessagesElem.empty();
			if (data.success) {
				ratingMessagesElem.append('<div class="success">Rating submitted.</div>');
			} else {
				for (var i = 0; i < data['messages'].length; i++) {
					ratingMessagesElem.append('<div class="' + data['messages'][i].type + '">' + data['messages'][i].code + '.</div>');
				}
			}

			setTimeout(function() {
				ratingMessagesElem.empty();
			}, 3000);
		}
	});
}

(function($) {
	$.fn.imagefit = function(options) {
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){
				$(img)
					.width('100%').each(function()
					{
						$(this).height(Math.round(
							$(this).attr('startheight')*($(this).width()/$(this).attr('startwidth')))
						);
					})
				}
		};

		this.each(function(){
				var container = this;

				// store list of contained images (excluding those in tables)
				var imgs = $('img', container).not($("table img"));

				// store initial dimensions on each image
				imgs.each(function(){
					$(this).attr('startwidth', $(this).width())
						.attr('startheight', $(this).height())
						.css('max-width', $(this).attr('startwidth')+"px");

					fit.one(this);
				});
				// Re-adjust when window width is changed
				$(window).bind('resize', function(){
					fit.all(imgs);
				});
			});
		return this;
	};
})(jQuery);


function submitRestockNotification()
{
    var product_id = jQuery('#product-field').val();
    var email_address = jQuery('#email-field').val();

    jQuery.ajax({
        url: '/restocknotification/index/addPost',
        type: 'post',
        data: {'product' : product_id, 'email' : email_address},
        dataType: 'json',
        success: function(data) {
            if (data.success) {
                jQuery('.field-error').hide();
                jQuery('#form-ui').hide();
                jQuery('#success-ui').html('<p class="success">' + data.message + '</p>');
                jQuery('#success-ui').show();
            }
            else {
                if (data.errors.general) {
                    var cnt = data.errors.general.length;
                    for (var i = 0; i < cnt; i++) {
                        jQuery('#form-errors').append('<p class="error">' + data.errors.general[i] + '</p>');
                    }
                    jQuery('#form-errors').show();
                }

                if (data.errors.fields) {
                    for (key in data.errors.fields) {
                        jQuery('#' + key + '-field-label').addClass('error');
                        jQuery('#' + key + '-field-error').html(data.errors.fields[key]).show();
                    }
                }
            }

            setTimeout(function () {jQuery(document).trigger('close.hardybox');}, 5000)
        },
        error: function(data) {
            jQuery('#form-errors').append('<p class="error">Restock notification request failed. Please try again.</p>');
        }
    });
}
jQuery.extend({
	  getUrlVars: function(){
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
	    {
	      hash = hashes[i].split('=');
	      vars.push(hash[0]);
	      vars[hash[0]] = hash[1];
	    }
	    return vars;
	  },
	  getUrlVar: function(name){
	    return jQuery.getUrlVars()[name];
	  }
	});
