// get everything ready on page load
$(document).ready( function()
{
$('#'+global.current+' a.nlink').css('background-position','bottom left');
$("#search").autocomplete('/assets/php/search.php', {
		width: 220,
		mustMatch: true,
		delay: 200,
		minChars: 2,
		selectFirst: true,
		max: 6
	});
$("#search_logged").autocomplete('/assets/php/search.php', {
		width: 220,
		mustMatch: true,
		delay: 200,
		minChars: 2,
		selectFirst: true,
		max: 6
	});
if ( $('#product-left').length ) {
		magnify();
		}
if ( $('#catalog_form').length ){
		cat_request();
}
if ( $('#slideform').length ) {
		request_form();
		}
if ( $('#date_form').length ) {
		$(".date_input").datepicker();
		date_form();
		}
if ( $('#check_it').length ) {
		$('#stock').val(['stock']);
		$('#front-three-a a').fancybox({
				'zoomSpeedIn':	0, 
				'zoomSpeedOut':	0,
				'frameHeight': 110
			});
		toggle_stock();
		}
if ( $('#large').length ) {
		rotate_images();
		}
$('a.req-info').click(function(){
	  $(this).fadeOut('fast');
	  $('#req-info-submit').val('Request');
      $('#slideform').slideDown();
      return false;
    });
$('a.cancel').click(function(){
      $('#slideform').slideUp();
      $('a.req-info').html('Request Information');
      $('a.req-info').wait(.5).then.fadeIn('fast');
      return false;
    });
if ($.cookie('sort_by') == null){
$.cookie('sort_by', 'product_num', { expires: 0, path: '/' });
$.cookie('sort_order', 'ASC', { expires: 0, path: '/' });
}
checkdealer();
showlink();
set_sort_links();
activeclass();
bind_search();
default_text();
menu_hover();
killIE();

if(global.current=='specials') showSpecials();

});



// site specific functions
function killIE(){
  if ($.cookie('killIE') != 'true'){
	if (jQuery.browser.msie) {
	var ie_version = parseInt(jQuery.browser.version);
		if (ie_version < 7){
		$.cookie('killIE', 'true', { expires: 0, path: '/' });
		window.location = '/ie6_is_bad';
		}
	}
	}
}
function showprice(){
$('.price_pop').toggle();
	if ($.cookie('shown') == 'true'){
	$.cookie('shown', null, { expires: 0, path: '/' });
	$('.show-prices').html('Show Details');
	$('.price_pop').css('display','');
	$(".aproduct").hover(
      function () {
        $(this).children('.price_pop').css('display','block');
      }, 
      function () {
        $(this).children('.price_pop').css('display','none');
      });
	} else {
	$.cookie('shown', 'true', { expires: 0, path: '/' });
	$('.show-prices').html('Hide Details');
	$(".aproduct").hover(
      function () {
        $(this).children('.price_pop').css('display','none');
      }, 
      function () {
        $(this).children('.price_pop').css('display','block');
      });
	}
}
function showSpecials(){
	$('.special').show();
	$('.show-prices').hide();
	$('.aproduct').hover(function(){
		$(this).children('.price_pop').css('display','none');
		},
		function(){
			$(this).children('.price_pop').css('display','block');
			});
	}
function bind_search(){
$('#topform').submit(function() {
		if ( $('#search_logged').length ) {
		var search_word = $('#search_logged').val().replace("/","");	
		} else { 
        var search_word = $('#search').val().replace("/","");
        }
        window.location = '/search/'+search_word;
        return false; 
    });
    }
function toggle_stock(){
	$('#stock-search').focus(function() {
	  if( this.value == 'Begin typing an item # here' ) {
		this.value = '';
	}
	});
	if ($.cookie('is_dealer') != 1){
	$('#stock-search').val('Dealers Log In to Check Stock');
	$('#check_it input').attr('disabled', true);
	}
	$('#parts').click(function(){
    $('#parts').val(['parts']);
    $('#stock').val(['none']);
    });
    $('#stock').click(function(){
    $('#stock').val(['stock']);
    $('#parts').val(['none']);
    });
	$("#stock-search").autocomplete('/assets/php/search.php', {
		width: 210,
		mustMatch: true,
		delay: 200,
		minChars: 2,
		selectFirst: true,
		max: 4
	});
	$('#check_it').submit(function() {
        var search_word = $('#stock-search').val().replace("/","");
        window.location = '/search/'+search_word;
        return false; 
    });
    }
function cat_request(){
	$('a.cancel').click(function(){
	parent.$("#fancy_outer").hide();
	parent.$("#fancy_content").hide().empty();
    });
}
function checkdealer(){
if ($.cookie('is_dealer') == 1){
	$('.dealer_show').show();
	decode_prices();
} else {
	$('#login').click(function(){
      $('#search').animate({
      	right: '-120px'
      }, 700 );
      $(this).replaceWith('<input type="submit" id="login" value="" />');
      $('#search').wait(1).then.replaceWith('<input type="text" id="logmein" name="logmein" value="Type Your Password Here" />');
      setTimeout('hideinput();dealer_form();',1100);
    });
	}
}
function decode_prices(){
	$('body').find('.price_pop .dealer_show,.display-price').each(function(i) {
	var price = $(this).html();
	var show_price = decode_letters(price);
	if ($(this).hasClass('display-price')) {
	$(this).html('$'+show_price);
	} else {
	$(this).html('/ $'+show_price);
	}
	});
}
function rotate_images(){
	$('#large').cycle({
    fx:      'fade',
    delay:   -3000,
    timeout: 6000,
    speed: 1700,
    pause: true,
    after:   onAfter
});
}
function onAfter() {
	var link = this.alt;
    $('#large').css('cursor','pointer').click(function(){
      window.location = "/collections/"+link;
    });
}
function menu_hover(){
	$('#collections ul').css('display','none');
	var config = {    
     sensitivity: 5,    
     interval: 100,    
     over: dropMenu,
     timeout: 300,   
     out: hideMenu  
	};
      function dropMenu() {
        $('#collections ul').slideDown(300);
      }
      function hideMenu() {
        $('#collections ul').fadeOut('fast');
      }
    $("#collections").hoverIntent( config );
}
function magnify(){
$('#product-left a.magnify').fancybox({
	'hideOnContentClick': true,
	'zoomSpeedIn': 300,
	'zoomSpeedOut': 300
	});
}
function set_sort_links(){
	$('#ASC').click(function(){
	  var ordertype = $(this).attr('rel');
	  var values = ordertype.split(' ');
      $.cookie('sort_order', 'ASC', { expires: 0, path: '/' });
      reload_sort(values[0],values[1]);
      return false;
      });
	$('#DESC').click(function(){
	  var ordertype = $(this).attr('rel');
	  var values = ordertype.split(' ');
      $.cookie('sort_order', 'DESC', { expires: 0, path: '/' });
      reload_sort(values[0],values[1]);
      return false;
    });
	$('#product_num').click(function(){
	  var ordertype = $(this).attr('rel');
	  var values = ordertype.split(' ');
      $.cookie('sort_by', 'product_num', { expires: 0, path: '/' });
      reload_sort(values[0],values[1]);
      return false;
    });
	$('#bulb_qty').click(function(){
	  var ordertype = $(this).attr('rel');
	  var values = ordertype.split(' ');
      $.cookie('sort_by', 'bulb_qty', { expires: 0, path: '/' });
      reload_sort(values[0],values[1]);
      return false;
    });
	$('#price').click(function(){
	  var ordertype = $(this).attr('rel');
	  var values = ordertype.split(' ');
      $.cookie('sort_by', 'price', { expires: 0, path: '/' });
      reload_sort(values[0],values[1]);
      return false;
    });
}
function activeclass(){
$('#sort-by a').removeClass('active');
var searchby = $.cookie('sort_by');
var order = $.cookie('sort_order');
$('#'+searchby+',#'+order+'').addClass('active');
}
function hideinput(){
$('#logmein').focus(function() {
	  if( this.value == 'Type Your Password Here' ) {
		this.value = '';
	}
	}).blur(function() {
	if( !this.value.length ) {
		this.value = this.defaultValue;
	}
	});
}
function default_text(){
$('#search,#logged_search').focus(function() {
	  if( this.value == 'Begin typing an item # here' ) {
		this.value = '';
	}
	});
}

function showlink(){
if ($.cookie('shown') == 'true'){
	$('.price_pop').css('display','block');
	$('.show-prices').html('Hide Details');
	$(".aproduct").hover(
      function () {
        $(this).children('.price_pop').css('display','none');
      }, 
      function () {
	$(this).children('.price_pop').css('display','block');
      }
    );
}
$('a.show-prices').click(function(){
      showprice();
      return false;
    });
}
function reload_sort(type,word){
var thispage = $('li a.active').html();
$.post('/assets/php/sort_return.php', { search_type: ''+type+'', search_word: ''+word+'', current_page: ''+thispage+'', path: ''+global.current+'' },
   function(data){
     $('#product_sort').html(data);
     $('.price_pop').show();
     $.cookie('shown', 'true', { expires: 0, path: '/' });
     $('.show-prices').html('Hide Details');
     set_sort_links();
     showlink();
     activeclass();
     checkdealer();
   });
}
function dealer_form(){
var options = { 
        beforeSubmit:  dealerWait,
        success:       dealerResponse,
        url:       '/assets/php/dealer_login.php' 
    }; 
    $('#topform').unbind();
    $('#topform').submit(function() {  
        $('#topform').ajaxSubmit(options); 
        return false; 
    });
}
function date_form(){
var options = { 
        success:       dateResponse,
        url:       '/assets/php/set_date.php' 
    }; 
    $('#date_form').submit(function() {  
        $('#date_form').ajaxSubmit(options); 
        return false; 
    });
}
function dateResponse(responseText){
	alert(responseText);
}
function dealerResponse(responseText){
	if (responseText == 'denied'){
	alert('Wrong Password Entered');
	$('#login').css('background-position','left top');
	} else {
	if ( $('#check_it').length ) {
	$('#check_it input').removeAttr('disabled');
	$('#stock-search').val('Begin typing an item # here'); 
	}
	$('#login').css('background-position','left -105px');
	if ( $('#slideform').length ) {
		$('.dealer_show').slideDown(700);
		} else {
	$('.dealer_show').show();
	$.cookie('shown', 'true', { expires: 0, path: '/' });
	$('.show-prices').html('Hide Details');
	$('.price_pop').show();
		}
	$('#login').wait(2).then.css('background-position','left -140px');
	$('#logmein').wait(2).then.replaceWith('<input type="text" id="search_logged" name="search" value="" />');
    $('#search-wrap').prepend('<a href="/?logout=true" id="logout" style="display:none;">(log out)</a>');
    $('#logout').wait(2).then.fadeIn();
    $('#topform').unbind();
    decode_prices();
    setTimeout('dealer_search();',2100);
	}
}
function dealerWait(){
	$('#login').css('background-position','left -70px');
}
function dealer_search(){
$("#search_logged").autocomplete('/assets/php/search.php', {
		width: 220,
		mustMatch: true,
		delay: 200,
		minChars: 2
	});
bind_search();
}
function request_form(){
var options = { 
        beforeSubmit:  requestWait,
        success:       requestResponse,
        url:       '/assets/php/info_request.php' 
    }; 

var v = jQuery("#request_form").validate({
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit(options);
			}
		});
}
function requestResponse(responseText){
	if (responseText == 'failed'){
	alert('There was a problem sending your request. Please try again later.');
	} else {
	$('#slideform').slideUp();
	$('a.req-info').html(responseText);
    $('a.req-info').wait(.5).then.fadeIn('fast');
    $("a.req-info").wait(.6).then.click(function() { return false; });
	}
}
function requestWait(){
	$('#req-info-submit').val('Sending...');
}

function decode_letters(price){
	var dealer_price = '';
	var price_show = new Array();
	var abc = 'abcdefghij';
	var lettercode = new Array(abc.length)
	for (var i = 0; i < abc.length; i++) {
	lettercode[i]= abc.charAt(i);
	}
	var stringA = price.replace('/ ',''); 
	var numberA = 0;
	for (var i = 0; i < stringA.length; i++) {
	var letter = stringA.charAt(i)
	for (var j = 0; j < lettercode.length; j++) {
		if (letter == lettercode[j]) {
		price_show.push(j);
		} 
	}
}
	for (var i = 0; i < stringA.length; i++) {
	dealer_price = dealer_price + price_show[i];
	}
	dealer_price = dealer_price * .01;
	dealer_price = roundNumber(dealer_price, 2);
	var temp_price = dealer_price  + "";
	var decimal_check = temp_price.split('.');
	  if (decimal_check[1]) {
		if (decimal_check[1].length < 2) {
		dealer_price = dealer_price + '0';
		}
		} else {
		dealer_price = dealer_price + '.00';
		}
	return dealer_price;
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

// method for chaining and pausing jquery events
var ChainCollector = function(base) {
var CLASS = arguments.callee;
this.then = this.and = this;
var queue = [], baseObject = base || {};
this.____ = function(method, args) {
queue.push({func: method, args: args});
};
this.fire = function(base) {
var object = base || baseObject, method, property;
for (var i = 0, n = queue.length; i < n; i++) {
method = queue[i];
if (object instanceof CLASS) {
object.____(method.func, method.args);
continue;
}
property = object[method.func];
object = (typeof property == 'function')
? property.apply(object, method.args)
: property;
}
return object;
};
};
ChainCollector.addMethods = function(object) {
var methods = [], property, i, n, name;
var self = this.prototype;
var reservedNames = [], blank = new this();
for (property in blank) reservedNames.push(property);
var re = new RegExp('^(?:' + reservedNames.join('|') + ')$j');
for (property in object) {
if (Number(property) != property)
methods.push(property);
}
if (object instanceof Array) {
for (i = 0, n = object.length; i < n; i++) {
if (typeof object[i] == 'string')
methods.push(object[i]);
}
}
for (i = 0, n = methods.length ; i < n; i++)
(function(name) {
if (re.test(name)) return;
self[name] = function() {
this.____(name, arguments);
return this;
};
})(methods[i]);
if (object.prototype)
this.addMethods(object.prototype);
};
jQuery.fn.wait = function(time) {
var collector = new ChainCollector(), self = this;
// Deal with scoping issues...
var fire = function() { collector.fire(self); };
setTimeout(fire, Number(time) * 1000);
return collector;
};
// Then extend ChainCollector with all jQuery's methods
ChainCollector.addMethods(jQuery);