//functions to create, read ande erase cookies
function createCookie(name,value,hours) {
  if (hours) {
    var date = new Date();
    date.setTime(date.getTime()+(hours*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}


function readCookie(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);
}



$(function() {
    // region selector
    if ($.browser.safari) {
        $("#search select")
            .css("color", "#ffffff")
            .css("background-color", "transparent");
    }
    $("#region").change(function() {
        if ($(this).val()) {
            Global.getJSONAction("ChangeRegion", {region_id: $(this).val(), location: location.href}, function(data) {
                location.href = data.response.location;
            });
        }
    });

    // search
    var search_graytext = (!$("#search_query_exists").length) ? $('#search_query').val() : '';
    var clear_graytext = function() {
        if (search_graytext && $('#search_query').val() && (search_graytext == $('#search_query').val()))
            $('#search_query').val('');
    };
    $("#search_query")
        .click(clear_graytext)
        .focus(clear_graytext)
        .blur(function() {
            if (search_graytext && ($(this).val() == ''))
                $(this).val(search_graytext);
        });
    $("#search")
        .submit(function() {
            clear_graytext();
            return true;
        });

    // support: category / model selector
    var cat_model_selector = function(bodyclass, valid_model_cb, invalid_model_cb) {
        valid_model_cb = (typeof(valid_model_cb) != "function") ? function() { } : valid_model_cb;
        invalid_model_cb = (typeof(invalid_model_cb) != "function") ? function() { } : invalid_model_cb;
        if ($("."+bodyclass+" #category").val() && $("."+bodyclass+" #model").val()) {
          createCookie('cat_cookie', $("."+bodyclass+" #category").val(), 1);
          createCookie('model_cookie', $("."+bodyclass+" #model").val(), 1);
        }
        $("."+bodyclass+" #category").change(function() {
            eraseCookie('cat_cookie');
            eraseCookie('model_cookie');
            invalid_model_cb();
            $("."+bodyclass+" #model").attr("disabled", "true");
            $("."+bodyclass+" #model").selectOptions($("."+bodyclass+" #model option:first").val());
            while ($("."+bodyclass+" #model option").length > 1) $("."+bodyclass+" #model").removeOption(1);
            if ($(this).val()) {
                Global.getJSONAction("GetModels", {cat_id: $(this).val()},
                    function(data) {
                        $("."+bodyclass+" #model").addOption(data.response.models, false);
                        $("."+bodyclass+" #model").removeAttr("disabled");
                    });
            } else {
                $("."+bodyclass+" #model").removeAttr("disabled");
            }
        });
        $("."+bodyclass+" #model").change(function() {
            if ($(this).val()) {
                createCookie('cat_cookie', $("."+bodyclass+" #category").val(), 1);
                createCookie('model_cookie', $("."+bodyclass+" #model").val(), 1);
                valid_model_cb($(this).val());
            } else{
                eraseCookie('cat_cookie');
                eraseCookie('model_cookie');
                invalid_model_cb($(this).val());
            }
        }).change();
    };

    // marketing support
    if ($('body.marketing').length) {
        $("#login_form #name").focus(function() {
            $(this).val('');
        });
        $("#login_form #text_password").focus(function() {
            $(this).hide();
            $("#login_form #password").show().focus(function() {
                $(this).val('');
            }).focus();
        });
    }
     $("body.marketing #password, body.marketing #name").keyup(function (e) {
     	var key_code = e.keyCode;
     	if(key_code == 13) {
     		$("#login_form").submit();
        return false;
     	}
     });

    $("body.insiders #email, body.insiders #password").keyup(function (e) {
     	var key_code = e.keyCode;
     	if(key_code == 13) {
     		$("#insiders_login_form").submit();
        return false;
     	}
     });


    // insiders
    if ($('body.insiders').length) {
        $("#insiders_login_form #email").focus(function() {
            $(this).val('');
        });

        $("#insiders_login_form #text_password").focus(function() {
            $(this).hide();
            $("#insiders_login_form #password").show().focus(function() {
                $(this).val('');
            }).focus();
        });
         $("#forget_password_form #forget_email").focus(function() {
            $(this).val('');
        });
    }

    // contact aoc
    $(".contact #contactAoc #contactaoc_submit").click(function() {
       $("#contactAoc").submit();
       return false;
    });
     $("#forget_password_form #reset_pw_enter").click(function() {
     	$("#forget_password_form").submit();
       return false;
     });

    // email a friend
    $(".contact #email  #email_friend_submit").click(function() {
       $("#email").submit();
       return false;
    });
    // career
    $(".contact #mailToJob").click(function() {
       $("#MailToJob").submit();
       return false;
    });

    $("#marketing_login_enter").click(function() {
    	if($("#login_form #name").val() == 'Username') {
    		$("#login_form #name").val('');
    	}
       $("#login_form").submit();
       return false;
    });
	$("#insiders_reg_submit").click(function() {
       	$("#join_club_form").submit();
        return false;
    });
    $("#ms_request").click(function() {
       	$("#support_request").submit();
        return false;
    });
    $("#insider_login_enter").click(function() {
    	$("#insiders_login_form").submit();
       return false;
    });

    $("#insider_login_enter").click(function() {
    	$("#edit_club_form").submit();
       return false;
    });



        $(".tech_support #country_list, .insiders #country_list").change(function() {
        	var country_id = $(this).val();
            if ($(this).val() == US_COUNTRY_ID || $(this).val() == CANADA_COUNTRY_ID ) {
            $("#state_list").removeOption(/./);
           	Global.getJSONAction("GetStateList", {country_id:country_id},
            function(data) {
                    $("#state_list").addOption(data.response.states, false);
             });
            $("#state").show();
            } else {
                $("#state").selectOptions($("#state option:first").val());
                $("#state").hide();
            }
        });
        if($(".insiders #country_list").val());
        {
        	var country_id = $(".insiders #country_list").val();
            if (country_id == US_COUNTRY_ID || country_id == CANADA_COUNTRY_ID ) {
        		$("#state").show();
           	 }
           	 else {
                $("#state").hide();
        	}
        }

    	if($(".insiders #company_country_list").val());
        {
        	var country_id = $(".insiders #company_country_list").val();
            if (country_id == US_COUNTRY_ID || country_id == CANADA_COUNTRY_ID ) {
        		$("#company_state").show();
           	 }
           	 else {
                $("#state").hide();
        	}
        }


 		$(".insiders #company_country_list").change(function() {
        	var country_id = $(this).val();
            if ($(this).val() == US_COUNTRY_ID || $(this).val() == CANADA_COUNTRY_ID ) {
            $("#company_state_list").removeOption(/./);
           	Global.getJSONAction("GetStateList", {country_id:country_id},
            function(data) {
                    $("#company_state_list").addOption(data.response.states, false);
             });
            $("#company_state").show();
            } else {
                $("#company_state_list").selectOptions($("#company_state_list option:first").val());
                $("#company_state").hide();
            }
        });

	  $("#insiders_unsubscribe_submit").click(function() {
 		  $("#insiders_unsubscribe").submit();
      return false;
 	  });
    
    // home: product registration
    if ($(".home").length) {
        $(".home #tools #prod_reg_prod").change(function() {
            if ($(this).val())
                location.href = "/support/product_registration/"+$(this).val();
        });
        if ($.browser.msie || $.browser.safari) {
            $(".home #tools #prod_reg_prod option").css("padding-left", "0");
            $(".home #tools #prod_reg_prod option:not(.empty)").prepend("&nbsp;&nbsp;&nbsp;&nbsp;");
        }
    }

    // home facebook + twitter
    if ($("body.home").length) {
      //var mouseover_lock = false;

      $('#facebook').click(function() {
        //if (!mouseover_lock) {
          $('#social_buttons').fadeOut('fast', function() {
            $('#social_links').fadeIn('fast');
            $('#social_links #fb').show();
          });
        //}
      });
      
      $('#twitter').click(function() {
        //if (!mouseover_lock) {
          $('#social_buttons').fadeOut('fast', function() {
            $('#social_links').fadeIn('fast');
            $('#social_links #tw').show();
          });
        //}
      });
      
      $('#fbtw_close').click(function() {
        //mouseover_lock = true;
        $('#social_links').fadeOut('fast', function() {
          $('#social_links ul').hide();
          $('#social_buttons').fadeIn('fast');
          //setTimeout(function() { mouseover_lock = false; }, 1000);
        });
      });       
    }
    
    // product registration
    if ($("body.registration").length) {
        cat_model_selector("registration", function(model) {
            $(".registration .more_info").hide();
            $(".registration #reg_form").show();
            Global.loadAction(".registration #aside #prod_info", "GetProductInfo", {id: model});
      }, function() {
            $(".registration .more_info").show();
            $(".registration #reg_form").hide();
        });

        $(".registration #country_list").change(function() {
        	var country_id	= $(this).val();
            if ($(this).val() == US_COUNTRY_ID || $(this).val() == CANADA_COUNTRY_ID ) {
            	$("#state_list").removeOption(/./);
            	 Global.getJSONAction("GetStateList", {country_id:country_id},
            	function(data) {
                     $("#state_list").addOption(data.response.states, false);
             });
                $("#state").show();
            } else {
                $("#state").selectOptions($("#state option:first").val());
                $("#state").hide();
            }
        }).change();

        $(".registration #reg_form #prod_reg_submit").click(function() {
            $("#selected_category").val($('#category').val());
            $("#selected_model").val($('#model').val());
            $("#reg_form").submit();
            return false;
        });
    }

     // accessories
     if ($("body.accessories").length) {
        cat_model_selector("accessories", function(model) {
            $(".accessories #reg_form").show();
            Global.loadAction(".accessories #aside #prod_info", "GetProductInfo", {id: model});
        },function(model) {
        $(".accessories #reg_form").hide();
        $(".accessories #aside #prod_info").empty();
        });

        $(".accessories #reg_form #accessories_submit").click(function() {
            $("#selected_category").val($('#category').val());
            $("#selected_model").val($('#model').val());
            $("#reg_form").submit();
            return false;
        });

      $('.accessories #content #main #reg_form #same_as_billing').click(function() {
         if($(this).val() == 1) {
            $('#shipping_fname').val('');
            $('#shipping_lname').val('');
            $('#shipping_street').val('');
            $('#shipping_city').val('');
            $('#shipping_state').val('');
            $('#shipping_country_list').val('');
            $('#shipping_zip').val('');
            $(this).val(0);
          } else {
           $('#shipping_fname').val($('#billing_fname').val());
            $('#shipping_lname').val($('#billing_lname').val());
            $('#shipping_street').val($('#billing_street').val());
            $('#shipping_city').val($('#billing_city').val());
            $('#shipping_state').val($('#billing_state').val());
            $('#shipping_country_list').val($('#billing_country_list').val());
            $('#shipping_zip').val($('#billing_zip').val());
            $(this).val(1);
          }
        });
      }

      // troubleshooting
      if ($("body.troubleshooting").length) {
        cat_model_selector("troubleshooting", function(model) {
          Global.loadAction(".troubleshooting #aside #prod_info", "GetProductInfo", {id: model});
          if ($(".troubleshooting #common_issues").length){
            Global.loadAction(".troubleshooting #common_issues", "GetCommonFixes", {id: model}, function() {
                $(".troubleshooting #issues dt").click(function() {
                    var id = $(this).attr("id").substr(6);
                    $("#issue_"+id).toggleClass("selected");
                    $("#issue_data_"+id).toggle();
                });
           });
          }
      }, function(model) {
               $(".troubleshooting #common_issues").empty();
               $(".troubleshooting #aside #prod_info").empty();
      });
      $('#issues dt').click(function () {
            $(this).toggleClass('selected');
            $(this).next().toggle();
      });
    }

    // warranty
    if ($("body.warranty").length) {
        cat_model_selector("warranty", function(model) {
        Global.loadAction(".warranty #tech_support_warranty", "GetWarranty", {id: model});
        Global.loadAction(".warranty #aside #prod_info", "GetProductInfo", {id: model});
        },function(model) {
         $(".warranty #tech_support_warranty").empty();
         $(".warranty #aside #prod_info").empty();
        });
    }

    // contact technical support
    if ($("body.contact_tech_support").length) {
        cat_model_selector("contact_tech_support", function(model) {
        Global.loadAction(".contact_tech_support #aside #prod_info", "GetProductInfo", {id: model});

      $(".contact_tech_support #form_contact").show();
            $(".contact_tech_support #support_submit").click(function() {
              $("#selected_category").val($('#category').val());
              $("#selected_model").val($('#model').val());
              $("#contact_support").submit();
              return false;
            });
        }, function(model) {
        $(".contact_tech_support #form_contact").hide();
        $(".contact_tech_support #aside #prod_info").empty();
      });
   }

/*

 // technical support
    if ($(".tech_support").length) {
        cat_model_selector("tech_support", function(model) {
          Global.loadAction(".tech_support #aside #prod_info", "GetProductInfo", {id: model});
        	if($(".tech_support #common_issues").length){
             	Global.loadAction(".tech_support #common_issues", "GetCommonFixes", {id: model}, function() {
               	 	$(".tech_support #issues dt").click(function() {
                    	var id = $(this).attr("id").substr(6);
                    	$("#issue_"+id).toggleClass("selected");
                    	$("#issue_data_"+id).toggle();
                	});
             });
          }

            $(".tech_support #form_contact").show();

            $(".tech_support #support_submit").click(function() {
            	$("#selected_category").val($('#category').val());
            	$("#selected_model").val($('#model').val());
            	$("#contact_support").submit();
            	return false;
            });
            //$(".tech_support #tech_support_intro").hide();

       	if($(".tech_support #tech_support_warranty").length){
            	Global.loadAction(".tech_support #tech_support_warranty", "GetWarranty", {id: model});
        }

        }, function(model) {
            //$(".tech_support #tech_support_intro").show();
            $(".tech_support #aside #tech_support_sidebar").show();
            $(".tech_support #form_contact").hide();
            $(".tech_support #common_issues").empty();
            $(".tech_support #aside #tech_support_drivers").remove();
            $(".tech_support #aside #tech_support_warranty").remove();

        });

        $('#issues dt').click(function () {
            $(this).toggleClass('selected');
            $(this).next().toggle();
        });
    }
*/
/*
    // technical support
    if ($(".tech_support").length) {
        cat_model_selector("tech_support", function(model) {
            Global.loadAction(".tech_support #common_issues", "GetCommonFixes", {id: model}, function() {
                $(".tech_support #issues dt").click(function() {
                    var id = $(this).attr("id").substr(6);
                    $("#issue_"+id).toggleClass("selected");
                    $("#issue_data_"+id).toggle();
                });
                $(".tech_support #form_contact").show();
                location.hash = "technical_support_form";

                $(".tech_support #support_submit").click(function() {
                    $("#selected_category").val($('#category').val());
                    $("#selected_model").val($('#model').val());
                    $("#contact_support").submit();
                    return false;
                });
                //$(".tech_support #tech_support_intro").hide();
            });
           // Global.loadAction(".tech_support #aside", "GetWarranty", {id: model}, function() {
            Global.loadAction(".tech_support #tech_support_warranty", "GetWarranty", {id: model}, function() {

              //  $(".tech_support #aside #tech_support_sidebar").hide();
                $(".tech_support #drivers").change(function() {
                    if ($(this).val())
                        location.href = $(".tech_support #dl_driver").attr("action")+$(this).val();
                });
            });
        }, function(model) {
            //$(".tech_support #tech_support_intro").show();
            $(".tech_support #aside #tech_support_sidebar").show();
            $(".tech_support #form_contact").hide();
            $(".tech_support #common_issues").empty();
            $(".tech_support #aside #tech_support_drivers").remove();
            $(".tech_support #aside #tech_support_warranty").remove();

        });

        $('#issues dt').click(function () {
            $(this).toggleClass('selected');
            $(this).next().toggle();
        });
    }

*/
    // manuals and drivers
    if ($("body.downloads #manuals_drivers").length) {
        cat_model_selector("downloads", function(model) {
            $(".downloads #aside #md_image").hide();
            Global.loadAction(".downloads #prod_info", "GetManualsandDrivers", {id: model});
            Global.loadAction(".downloads #aside #md_content","GetPdfManualsAndDrivers", {id: model}, function() {
                $(".downloads #drivers").change(function() {
                    if ($(this).val())
                        location.href = $(".downloads #dl_driver").attr("action")+$(this).val();
                });
            });
        }, function(model) {
            $(".downloads #prod_info").empty();
            $(".downloads #aside #md_image").show();
            $(".downloads #aside #md_content").empty();
        });
    }

  // support downloads
    if ($("body.downloads #support_downloads").length) {
        cat_model_selector("downloads", function(model) {
            $(".downloads .more_info").hide();
            $(".downloads #aside").show();
            $(".downloads #dl_preview").show();
            Global.loadAction(".downloads #dl_preview", "GetSupportDownload", {id: model}, function() {
               $("#dl_preview ul li a").click(function() {
                    var p_id = $(this).attr("id").substr(1);
                    $("#dl_preview ol li:lt(2) a").each(function() {
                        var p_href = $(this).attr("href");
                        $(this).attr("href", p_href.substr(0, p_href.lastIndexOf("/"))+"/"+p_id);
                    });
                    $("#dl_preview #small_image img").attr("src", $(this).attr("href"));
                    $("#dl_preview ul li").removeClass("selected");
                    $(this).parent().addClass("selected");
                    return false;
                });
            });
        }, function(model) {
             $(".downloads .more_info").show();
             $(".downloads #dl_preview")
                .empty()
                .hide();
             $(".downloads #aside").hide();
        });
    }


    // press downloads
    if ($("body.press #press_downloads").length) {
        cat_model_selector("press", function(model) {
            $(".press #dl_logo").hide();
            $(".press #dl_preview").show();
            Global.loadAction(".press #dl_details #dl_prod", "GetPressDownloadProduct", {id: model});
            Global.loadAction(".press #dl_preview", "GetPressDownload", {id: model}, function() {
                $("#dl_preview ul li a").click(function() {
                    var p_id = $(this).attr("id").substr(1);
                    $("#dl_preview ol li:lt(2) a").each(function() {
                        var p_href = $(this).attr("href");
                        $(this).attr("href", p_href.substr(0, p_href.lastIndexOf("/"))+"/"+p_id);
                    });
                    $("#dl_preview #small_image img").attr("src", $(this).attr("href"));
                    $("#dl_preview ul li").removeClass("selected");
                    $(this).parent().addClass("selected");
                    return false;
                });
            });
        }, function(model) {
            $(".press #dl_logo").show();
            $(".press #dl_details #dl_prod").empty();
            $(".press #dl_preview")
                .empty()
                .hide();
        });
    }

    // press news articles
    if ($(".press .news").length) {
          $(".press .news h3 a").live("click", function(){
            $(".press .news #aside").empty();
            var article_id = $(this).attr("href").substr($(this).attr("href").lastIndexOf("/")+1);
            Global.loadAction(".press .news #aside", "GetNewsArticle", {id: article_id});
            return false;
        });
    }

    // product tabs
    //$('.tab_content').hide();
    var current_url = document.location.toString();
    if (current_url.match('#')) {
        var current_tab = '#' + current_url.split('#')[1];
        $('.tabs li a').each(function () {
            var tabs_link = $(this).attr('href');
            if (tabs_link == current_tab) $(this).parent().addClass('selected');
        });
        $(current_tab).show();
    } else {
        $('#details').fadeTo(0, 1).show();
        $('.tabs li:first').addClass('selected');
    }

    $('.tabs li a').click(function () {
        $('.tabs li').removeClass('selected');
        $(this).parent().addClass('selected');
        $('.tab_content').hide();
        var content_id = ($(this).attr('id').substr(2)); // strip off "p_"
      
        if (content_id != 'online') {
          $('#buy_online_shortcut').removeClass('selected');
        } else if (!$('#buy_online_shortcut').attr('class')) {
          $('#buy_online_shortcut').addClass('selected');
        }
     
        var load_cb = function() {
            $("#"+content_id).fadeIn();
            $('.tab_content').each(function() {
                if ($(this).attr("id") != content_id) $(this).hide();
            });
        };
        switch (content_id) {
            case "details":
                if ($("#details").html())
                    load_cb();
                else
                    Global.loadAction("#details", "GetProductDetail", {id: $("#tabs_prod_id").val()}, load_cb);
                break;
            case "tech_specs":
                if ($("#tech_specs").html())
                    load_cb();
                else
                    Global.loadAction("#tech_specs", "GetTechSpecification", {id: $("#tabs_prod_id").val(), category: $("#tabs_cat_url").val()}, load_cb);
                break;
            case "support":
                if ($("#support").html())
                    load_cb();
                else
                    Global.loadAction("#support", "GetProductSupport", {id: $("#tabs_prod_id").val()}, load_cb);
                break;
           case "reviews":
                if ($("#reviews").html())
                    load_cb();
                else
                    Global.loadAction("#reviews", "GetProductReviews", {id: $("#tabs_prod_id").val()}, load_cb);
                break;     
           case "accessories":
                if ($("#accessories").html())
                    load_cb();
                else
                    Global.loadAction("#accessories", "GetRecommendedAccessories", {id: $("#tabs_prod_id").val()}, load_cb);
                break;
            case "online":
                if ($("#online").html()) {
                    load_cb();
                } else {
                    Global.loadAction("#online", "BuyOnline", {id: $("#tabs_prod_id").val()}, load_cb);
                }
                break;
        }
        return false;
    });


    // handling buy online shortcut button (next to share button on product pages)
     $('#buy_online_shortcut').click(function () {
       $('#buy_online_shortcut').addClass('selected');
        var load_cbs = function() {
            $('.tabs li').removeClass('selected');
            $('#buy_online').addClass('selected');
            $('.tab_content').each(function() { if ($(this).attr("id") != 'online') $(this).hide(); });
            $("#online").fadeIn();
            location.href = "#buy_online";
        };
        if ($("#online").html()) {
          load_cbs();
        } else {
          Global.loadAction("#online", "BuyOnline", {id: $("#tabs_prod_id").val()}, load_cbs);
        }
    });


   // product share
   if ($("body.product").length == 1) {
      prod_name = $('.prod_name').html();
      //prod_name = prod_name.toUpperCase();
      share_title = 'Check out the '+prod_name+' from AOC';

      var addthis_config = {
        ui_cobrand: "AOC",
        ui_header_color: "#FFFFFF",
        ui_header_background: "#1F1F1F",
        data_track_linkback: true,
        services_compact: "email, print, facebook, twitter, stumbleupon, favorites, google, myspace, digg, live, delicious, reddit, blogger, tumblr",
        services_expanded: "email, print, facebook, twitter, stumbleupon, favorites, google, myspace, digg, live, delicious, reddit, blogger, tumblr, orkut, linkedin, gmail, yahoomail, hotmail, aolmail, technorati, buzz"
      };

      var addthis_share = {
          title: share_title, 
          templates: {twitter: '{{title}}: {{url}}'},
          description: '',
          screenshot: ''
        };

      addthis.button(".addthis_button", addthis_config, addthis_share);
   }

    // product photos
    if ($(".product .product_thumbs ul").length) {
        $(".product .product_thumbs ul .full_image_thumb").each(function() {
            $(this)
                .click(function() {
                    $(".full_img img").attr("src", $(this).attr("href"));
                    $(".full_img a").attr("href", $(this).attr("href").replace('_medium', '_large'));
                    $(".product_thumbs ul li").removeClass("selected");
                    $(this).parent().addClass("selected");
                    return false;
                });
        });
    }
    // product compare
    $("#compare").change(function() {
        if ($(this).val()) {
            location.href = BASE_URL + "compare/" + $("#compare_current_prod").val() + "/" + $(this).val();
        }
    });
    // event photo gallery
    if ($(".events_gallery #slides").length) {
        var cur_img = 0;
        var slide_count = $(".events_gallery #slides #slide_images li").length;

        var set_gallery_image = function() {
            $(".events_gallery #slides #slide_images li")
                .hide()
                .filter(":eq("+cur_img+")")
                .show();
            set_gallery_nav();
        };

        var set_gallery_nav = function() {
            if (cur_img == 0) {
                $(".prev a")
                    .css("cursor", "default")
                    .addClass("disabled");
                $(".prev")
                    .mouseover(function() { return false; })
                    .unbind('click')
                    .click(function() { return false; });
            } else {
                $(".prev a")
                    .css("cursor", "pointer")
                    .removeClass("disabled");
                $(".prev")
                    .unbind('click')
                    .click(function() {
                        cur_img--;
                        set_gallery_image();
                        return false;
                    })
            }
            if (cur_img == (slide_count - 1)) {
                $(".next a")
                    .css("cursor", "default")
                    .addClass("disabled");
                $(".next")
                    .mouseover(function() { return false; })
                    .unbind('click')
                    .click(function() { return false; });
            } else {
                $(".next a")
                    .css("cursor", "pointer")
                    .removeClass("disabled");
                $(".next")
                    .unbind('click')
                    .click(function() {
                        cur_img++;
                        set_gallery_image();
                        return false;
                    })
            }
        };

        set_gallery_image();
    }

    // retailers + resellers
    if ($(".selector #country").length) {
         var table;
         if ($(".retailers").length) table = 'rsc_wtb_retailers';
         else if ($(".resellers").length) table = 'rsc_wtb_resellers';
         else if ($(".find").length) table = 'rsc_service_centers';

         if (table) {
            var get_resellers = function(city, state_id, country_id) { Global.loadAction("#search_results", "GetSpecialResellers", {city: city, state_id: state_id, country_id: country_id}); };
            var get_retailers = function(city, state_id, country_id) { Global.loadAction("#search_results", "GetRetailers", {city: city, state_id: state_id, country_id: country_id}); }
            var get_find_service_center = function(city, state_id, country_id) { Global.loadAction("#search_results", "GetServiceCenter", {city: city, state_id: state_id, country_id: country_id}); }
            var wtb_cookies = false;
            var wtb_cookie_exp = 30; // days

            var COOKIE_NAME = 'aoc_' + table + '_country';
            if ($.cookie(COOKIE_NAME) && wtb_cookies) $("#country").val($.cookie(COOKIE_NAME));

            var country_change = function() {
                $("#search_results, #statebox, #citybox").hide();
                $("#state, #city").attr("disabled", "true");
                if ($("#country").val()) {
                    var COOKIE_NAME = 'aoc_'+table+'_country';
                    $.cookie(COOKIE_NAME, $("#country").val(), {expires: wtb_cookie_exp});
                    if ($("#country").val() == US_COUNTRY_ID) {
                        $("#statebox").show();
                        $("#state").selectOptions($("#state option:first").val());
                        while ($("#state option").length > 1) $("#state").removeOption(1);
                        Global.getJSONAction("GetStatesForTable", {country_id: $("#country").val(), table: table},
                            function(data) {
                                $("#state").addOption(data.response.states, false);
                                var COOKIE_NAME = 'aoc_'+table+'_state';
                                if ($.cookie(COOKIE_NAME) && wtb_cookies) $("#state").val($.cookie(COOKIE_NAME));
                                $("#state").removeAttr("disabled");
                                $("#state").change(function() {
                                    if ($(this).val()) {
                                        change_to_city(table, $("#country").val(), $("#state").val());
                                    } else {
                                        $("#citybox").hide();
                                        $("#city").attr("disabled", "true");
                                    }
                                }).change();
                            });
                    } else {
                        change_to_city(table, $("#country").val());
                    }
                }
            };

            var change_to_city = function(table, country_id, state_id) {
                if (typeof(state_id) == "undefined") state_id = '';
                if (state_id) {
                    var COOKIE_NAME = 'aoc_'+table+'_state';
                    $.cookie(COOKIE_NAME, state_id, {expires: wtb_cookie_exp});
                }
                $("#citybox").show();
                $("#city").attr("disabled", "true");
                $("#city").selectOptions($("#city option:first").val());
                while ($("#city option").length > 1) $("#city").removeOption(1);
                Global.getJSONAction("GetCitiesForTable", {country_id: country_id, state_id: state_id, table: table},
                    function(data) {
                        $("#city").addOption(data.response.cities, false);
                        var COOKIE_NAME = 'aoc_'+table+'_city';
                        if ($.cookie(COOKIE_NAME) && wtb_cookies) $("#city").val($.cookie(COOKIE_NAME));
                        $("#city").removeAttr("disabled");
                        var city_change = function() {
                            $("#search_results").empty().hide();
                            var COOKIE_NAME = 'aoc_'+table+'_city';
                            $.cookie(COOKIE_NAME, $("#city").val(), {expires: wtb_cookie_exp});
                            if ($("#city").val()) {
                                $("#search_results").show();
                                if ($(".retailers").length) get_retailers($("#city").val(), state_id, country_id);
                                if ($(".resellers").length) get_resellers($("#city").val(), state_id, country_id)
                                if ($(".find").length)      get_find_service_center($("#city").val(), state_id, country_id);;
                            }
                        };
                        $("#city")
                            .unbind()
                            .change(city_change)
                            .change();
                   });
            };

            $("#country").change(country_change);
         }
   }

    // back links
    $(".back_link").click(function() {
        history.go(-1);
    });

    // news ticker
    var news_count = $(".home #news #ticker li").length;
    if (news_count) {
        var news_fade_delay = 2500;
        var news_fade_speed = 'slow';
        var news_index = 0;
        $(".home #news #ticker li:eq("+news_index+")").show();
        var news_tick = function() {
            $(".home #news #ticker li:eq("+news_index+")").fadeOut(news_fade_speed, function() {
                news_index++;
                if (news_index == news_count) news_index = 0;
                $(".home #news #ticker li:eq("+news_index+")").fadeIn(news_fade_speed, function() {
                    setTimeout(news_tick, news_fade_delay);
                });
            });
        };
        setTimeout(news_tick, news_fade_delay);
    }



    // interactive shopping guide
    $(".guide #aside").scrollFollow()
    { container: 'outer' };	// why doesn't this work inside the scrollFollow() function above?
    $(".guide #isg_guide .clickable").click(function () {
        $(this).parent().toggleClass('selected');
    });
    $(".guide #isg_guide input:checkbox").click(function() {
        var cat_id = $("#category_id").val();
        var selected_options = [];
        $(".guide #isg_guide input:checkbox:checked").each(function() {
            selected_options.push($(this).val());
        });
        selected_options = selected_options.join(",");
        Global.loadAction(".guide #aside", "GetIsgProducts", {option_ids: selected_options, category_id: cat_id});
    });
    $(".guide #isg_guide #submit a").click(function() {
        $(".guide #isg_guide input:checkbox:checked").each(function() {
            $(this).removeAttr("checked");
        });
        $(".guide #isg_guide li.selected").removeClass("selected");
        $(".guide #aside").html("");
    });

    // contact character count
    var content = $("#contact_message").val();
      	if(content) {
      		max_chars = 500;
      		var content_length = content.replace(/\s+/g, '').length;
      		 var remaining_chars = max_chars - content_length;
      		jQuery("#char_limit").html(remaining_chars);
      	}

    $("#contact_message").keyup(function (e) {
	    var key_code = e.keyCode;
	    var max_chars = 500;
	    var content = $("#contact_message").val();
	    var content_length = content.replace(/\s+/g, '').length;
	    var remaining_chars = max_chars - content_length;
	   	jQuery("#char_limit").html(remaining_chars);

	    if(key_code == 8 || key_code == 46) {
			jQuery("#contact_remaining_chars").css("color", "");
			return true;
		}
		if ((key_code == '32') || (key_code == '37')  || (key_code == '38')
	            || (key_code == '39') || (key_code == '40'))  {
					return true;
				}
	    });
});
