$(document).ready(function(){

	//  MAIN NAV
	$('#main_nav li').mouseover(function() {
		$(this).find('.nav_size').css( 'display', 'block' );
	});

	$('#main_nav li').mouseout(function() {
		$(this).find('.nav_size').css( 'display', 'none' );
	});

	//  CATEGORY MOUSE OVERS
	$('.category_sub_list li.animate').mouseover(function() {
		$(this).addClass( 'over' );
	});

	$('.category_sub_list li.animate').mouseout(function() {
		$(this).removeClass( 'over' );
	});

	//  Disable all form autocompleting (for security)
	disableAutoComplete();
});

//  DISABLE ALL FORM AUTOCOMPLETING
function disableAutoComplete() {
	if( !( document.forms && document.forms.length > 0 ) ) {
		return;
	}

	for( var i = 0; i < document.forms.length; i++ ) {
		if( !( document.forms[i] && document.forms[i].elements && document.forms[i].elements.length > 0 ) ) {
			continue;
		}
		for( var j = 0; j < document.forms[i].elements.length; j++ ) {
			document.forms[i].elements[j].setAttribute( 'autocomplete', 'off' );
		}
	}
}

// CONTRACT/EXPAND A CATEGORY
function catContract( cnt ) {
	if( $('#'+cnt).find( '.category_sub_list' ).css( 'display' ) == "block" ) {
		$('#'+cnt).find( '.category_sub_list' ).slideUp();
		$('#'+cnt).find( '.category_sub_list_header .arrow' ).attr( 'src', '/images/cat_arraw_right.gif' );
	} else {
		$('#'+cnt).find( '.category_sub_list' ).slideDown();
		$('#'+cnt).find( '.category_sub_list_header .arrow' ).attr( 'src', '/images/cat_arraw_down.gif' );
	}
}

//  PRODUCT TABS
function toggleProductTab( cnt ) {

	$('div.details_container').css( 'display', 'none' );
	$('li.prod_tab').removeClass( 'on' );

	var id_cnt = $(cnt).attr( 'id' ) + "_cnt";

	$('#'+id_cnt).css( 'display', 'block' );
	$('#'+$(cnt).attr( 'id' )).addClass( 'on' );
}

//  ADD ITEM POPUP
$(function(){
	var page_popup = function(){
		showPagePopup();
		//$('#page_screen_box').css({'display': 'block', opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
		//$('body').css({'overflow':'hidden'});
		//$('#page_popup_box').css({'display': 'block'}).click(function(){$(this).css('display', 'none');$('#page_screen_box').css('display', 'none')});
	}
	$('#button').click(page_popup);
});

function showPagePopup() {
	$('#page_screen_box').css({'display': 'block', opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	//$('body').css({'overflow':'hidden'});
	$('#page_popup_box').css({'display': 'block'});
	$('#page_popup_box').html( $('#page_popup_box').html() + '<a href="javascript: void(0);" onclick="closePagePopup();"><img id="page_popup_box_close" src="/images/popup_close.gif" /></a>' );

	$('#item_added_continue_shopping').focus();
}

function closePagePopup() {
	$('#page_popup_box').css({'display': 'block'}).click(function(){$(this).css('display', 'none');$('#page_screen_box').css('display', 'none')});
}

//  UPDATE THE 'VIEW CART' BUTTON CONTENT.
function updateViewCart() {

	$.get("/order/json-cart-summary/", function(data){

		var summary = eval( '('+data+')' );

		if( summary && typeof( summary.line_count ) != 'undefined' && summary.line_count > 0 ) {
			$('#header_view_cart_count').html( '(' + summary.line_count+ ')' );
			$('#header_view_cart').css( 'display', 'block' );

			//  On the order summary page, update the sub-total.
			if( $('#order_sub_total') ) {
				$('#order_sub_total').html( summary.sub_total);
			}

			//  Shipping.
			if( summary.shipping > 0.00 ) {
				$('#order_shipping').html( summary.shipping );
				$('#shipping_cnt').css( 'display', 'block' );
			} else {
				$('#shipping_cnt').css( 'display', 'none' );
			}
		} else {
			$('#header_view_cart').css( 'display', 'none' );
		}
	});
}

//  ADD AN ITEM TO A CART
function addItemToCart( sku_idx ) {
	$.post("/product/add-to-cart/", {
		product_sku_idx: sku_idx,
		from_category: ( ( typeof( from_category ) != 'undefined' ) ? from_category : '' ),
		other_info: "other info" },
	function(data){
		updateViewCart();
		$('#page_popup_box').html( data );
		showPagePopup();
	});
}

//  DELETE A CART LINEITEM
function deleteCartItem( line_idx ) {

	$.post("/order/delete-cart-item/", {
		line_idx: line_idx },
	function(data){
		updateViewCart();
	});

	closePagePopup();
}

//  CHANGE A CART QUANTITY
function cartChangeQty( line_idx, fld, old_qty ) {

	if( !( Number( line_idx ) && Number( line_idx ) > 0 && fld && Number( $(fld).val() ) == $(fld).val() && $(fld).val() != '' ) ) {
		return;
	}

	var url = "/order/change-cart-qty/?line_idx=" + Number( line_idx ) + "&qty=" + Number( $(fld).val() );

	$('#qty_notice_'+line_idx).html( 'updating quantity' );

	$.get( url, function(data){

		var summary = eval( '('+data+')' );

		//  Error?
		if( summary && typeof( summary.error ) != 'undefined' && summary.error ) {
			$('#qty_notice_'+line_idx).html( summary.error );

			if( summary && typeof( summary.total_inv ) != 'undefined' && summary.total_inv ) {
				$(fld).val( summary.total_inv );
			}

			return;
		}

		if( summary && typeof( summary.idx ) != 'undefined' && summary.idx > 0 ) {

			if( summary.total_lines <= 0 ) {
				document.location = '/order/';
				return;
			}

			//  Deleted?
			if( summary.is_deleted == 1 ) {
				$('#cart_line_'+line_idx).css( 'display', 'none' );
			}

			//  Update the notice.
            if( typeof( summary.message ) != 'undefined' && summary.message != '' ) {
				$('#qty_notice_'+line_idx).html( summary.message );
			} else {
				$('#qty_notice_'+line_idx).html( 'quantity updated' );
			}

			$(fld).val( summary.new_qty );
			$('#'+line_idx+'_inventory').html( summary.inventory );

			//  Update the price
			$('#price_'+line_idx).html( summary.price );

			//  Update the total price
			$('#total_'+line_idx).html( summary.total_price );

		} else {
			$('#qty_notice_'+line_idx).html( '' );
		}

		updateViewCart();
	});
}

// CHANGE THE SHIPPING ADDRESS TYPE
function changeShippingType( el ) {
	if( $(el).val() == "usa" ) {
		$('#delivery_address_usa').css( 'display', 'block' );
		$('#delivery_address_intl').css( 'display', 'none' );
	} else {
		$('#delivery_address_usa').css( 'display', 'none' );
		$('#delivery_address_intl').css( 'display', 'block' );
	}
}

//  CHANGE THE PAYMENT TYPE
function changePaymentType() {
	if( $('#payment_type_usa').attr( 'checked' ) ) {
		$('#payment_address_us').css( 'display', 'block' );
		$('#payment_address_intl').css( 'display', 'none' );
	} else {
		$('#payment_address_us').css( 'display', 'none' );
		$('#payment_address_intl').css( 'display', 'block' );
	}
}

//  ON THE BILLING FORM, USE THE SHIPPING INFORMATION
function billingUseShipping( el, ship_data ) {

	//  Not checked, clear the fielkds.
	if( !$(el).attr( 'checked' ) ) {
		for( var i = 0; i <= document.forms[ 'billing_form' ].elements.length; i++ ) {
			var fld = document.forms[ 'billing_form' ].elements[i];

			if( !( fld && fld.name && fld.name != '' ) ) {
				continue;
			}
			
			if( fld.name.toString().match( /^billing\[.*\]$/ ) ) {
				$(fld).val( '' );
			}
		}
		return;
	}

	if( !( addr_vals = ship_data.split( "^^^" ) ) ) {
		return;
	}

	//  International?
	var intl = false;
	for( var i = 0; i <= addr_vals.length; i++ ) {
		if( addr_vals[i] && addr_vals[i].split( "*||*" )[0] == 'geo_country_idx' && addr_vals[i].split( "*||*" )[1] != 1 ) {
			intl = true;
		}
	}

	//  Show either INTL or USA
	if( intl ) {
		$('#payment_type_intl').attr( 'checked', true );
		changePaymentType();
	} else {
		$('#payment_type_usa').attr( 'checked', true );
		changePaymentType();
	}

	//  Fill the form fields.
	for( var i = 0; i <= addr_vals.length; i++ ) {

		if( !addr_vals[i] ) {
			continue;
		}

		val = addr_vals[i].split( "*||*" );
		val_field = val[0];
		val_value = val[1];

		//  Set the standard values.
		form_field = document.forms[ 'billing_form' ].elements[ 'billing['+val_field+']' ] ;
		if( form_field ) { $(form_field).val( val_value ); }

		//  Set the USA values
		form_field = document.forms[ 'billing_form' ].elements[ 'billing[usa]['+val_field+']' ] ;
		if( form_field ) { $(form_field).val( val_value ); }

		//  Set the INTL values
		form_field = document.forms[ 'billing_form' ].elements[ 'billing[intl]['+val_field+']' ] ;
		if( form_field ) { $(form_field).val( val_value ); }
	}
}

//  SWAP THE PRODUCT IMAGE (ON THE PRODUCT PAGE) FOR EACH NEW COLOR
var new_product_image;
function swapProductColor( color_idx ) {

	if( !$('#product_image').attr( 'src' ) ) {
		return;
	}

	//  Load the new product image.
	var new_src = $('#product_image').attr( 'src' ).toString().replace( /(.*-)(\d+)(-\d+[x]\d+\.jpg)/, ( "$1" + color_idx + "$3" ) );
	new_product_image = new Image();
	new_product_image.onload = loadProductImage;
	new_product_image.src = new_src;
}

//  SWAP THE PRODUCT IMAGE (ON THE PRODUCT PAGE) FOR EACH NEW COLOR
function loadProductImage() {
	$('#product_image').attr( 'src', new_product_image.src );

	//  Load the zoomable image.
	var zoom_src = $('#product_image').attr( 'src' ).toString().replace( /(.*-\d+-)(\d+[x]\d+)(\.jpg)/, ( "$1" + "1630x1830" + "$3" ) );
	$('#product_image_href').attr( 'href', zoom_src );

	//  Restart the zooming for this image.
	$('.cloud-zoom').CloudZoom();
}

//  LOAD A SHIPPING ADDRESS
function loadShippingAddress( addr ) {

	//  Nothing? clear the form.
	if( !addr || !$(addr).val() ) {
		for( var i = 0; i < document.forms[ 'shipping_form' ].elements.length; i++ ) {
			if( document.forms[ 'shipping_form' ].elements[i].name != 'ship[type]' ) {
				$(document.forms[ 'shipping_form' ].elements[i]).val( '' );
			}
		}

		$('#ship_type_usa').attr( 'checked', true );
		$('#is_store_shipment').attr( 'checked', true );

		$('#city_state_cnt').html( '' );
		changeShippingType( document.getElementById( 'ship_type_usa' ), false )
		return;
	}

	addr_vals = $(addr).val().toString().split( "^^^" );

	if( !addr_vals ) {
	}

	var intl = false;
	for( var i = 0; i <= addr_vals.length; i++ ) {
		if( addr_vals[i] && addr_vals[i].split( "*||*" )[0] == 'geo_country_idx' && addr_vals[i].split( "*||*" )[1] != 1 ) {
			intl = true;
		}
	}

	if( intl ) {
		$('#ship_type_intl').attr( 'checked', true );
		changeShippingType( document.getElementById( 'ship_type_intl' ), false );
	} else {
		$('#ship_type_usa').attr( 'checked', true );
		changeShippingType( document.getElementById( 'ship_type_usa' ), false );
	}

	shipping_city = '';

	//  Fill in the values.
	for( var i = 0; i <= addr_vals.length; i++ ) {

		if( !addr_vals[i] ) {
			continue;
		}

		val = addr_vals[i].split( "*||*" );
		val_field = val[0];
		val_value = val[1];

		if( val_field == 'city' ) {
			shipping_city = val_value;
		}

		//  Set the value.
		if( form_field = document.forms[ 'shipping_form' ].elements[ 'ship['+val_field+']' ] ) {
			$(form_field).val( val_value );
		}

		//  USA...
		if( form_field = document.forms[ 'shipping_form' ].elements[ 'ship[usa]['+val_field+']' ] ) {
			$(form_field).val( val_value );
		}

		//  INTL...
		if( form_field = document.forms[ 'shipping_form' ].elements[ 'ship[intl]['+val_field+']' ] ) {
			$(form_field).val( val_value );
		} 
	}

	if( !intl ) {
		loadRecipCityState( shipping_city );
	}
}

//  CHECKOUT
var checkout_clicked = false;
function processOrder() {
	if( !checkout_clicked ) {
		checkout_clicked = true;
		document.forms[ 'billing_form' ].submit();
	}
	return false;
}

//  SPECIAL INSTRUCTIONS COUNTER
function shippingSpecialInstructionsCounter( max, box ) {

	var cur_count = $(box).val().length;
	var remaining = max - cur_count;

	if( remaining <= 0 ) {
		remaining = 0;
	}

	$('#special_inst_count').html( remaining );

	if( remaining == 0 ) {
		$(box).val( $(box).val().toString().substr( 0, max ) )
	}
}

//  TOGGLE FAQ
function toggleFaq( idx ) {
	if( $('#answer_'+idx).css( 'display' ) == 'none' ) {
		$('#answer_'+idx).slideDown();
	} else {
		$('#answer_'+idx).slideUp();
	}
}

//  STORE SEARCH
function storeSearch( form ) {

	var go = false;

	//  Do the fields have anything?
	for( var i = 0; i <= form.elements.length; i++ ) {
		var fld = form.elements[i];
		if( $(fld).val() && $(fld).val() != '' ) {
			go = true;
		}
	}

	var error_msg = '';

	if( !( go && GBrowserIsCompatible() ) ) {
		showStoreSearchErrors( "Please provide search criteria." );
		return;
	}

	//  Only a state
	if( $(form.elements[ 'state' ]).val() != '' && $(form.elements[ 'address' ]).val() == "" && $(form.elements[ 'city' ]).val() == "" && $(form.elements[ 'zip' ]).val() == "" ) {
		document.location = "/stores/" + $(form.elements[ 'state' ]).val();
		return;
	}

	//  Check the address.
	if( $(form.elements[ 'address' ]).val() && !( $(form.elements[ 'city' ]).val() != "" && $(form.elements[ 'state' ]).val() != "" ) ) {
		showStoreSearchErrors( "Please also provide a City and State to perform your search." );
		return;
	}

	//  Check the zip code.
	if( $(form.elements[ 'zip' ]).val() != '' && !$(form.elements[ 'zip' ]).val().match( /\d{5}/ ) ) {
		showStoreSearchErrors( "Please provide a valid zip code." );
		return;
	}

	//  Build the map.
	geocoder = new GClientGeocoder();

	if( $(form.elements[ 'zip' ]).val() != '' ) {
		address = $(form.elements[ 'zip' ]).val();
	} else {
		address = $(form.elements[ 'address' ]).val() + ", " + $(form.elements[ 'city' ]).val() + ", " + $(form.elements[ 'state' ]).val();
	}

	//  Get the lat and long of the address and then load the map.
	geocoder.getLatLng( address, function(start_point) {

		//  Get the LAT and LONG.
		regex = /^\(([0-9-.]+), (.*)\)$/;
		start_lat = start_point.toString().replace( regex, "$1" );
		start_long = start_point.toString().replace( regex, "$2" );

		if( !( start_lat && start_long ) ) {
			showStoreSearchErrors( "The address you entered could not be found." );
			return;
		}

		document.location = "/stores/search/?lat=" + start_lat + "&long=" + start_long +
			"&address=" + encodeURIComponent( $(form.elements[ 'address' ]).val() ) +
			"&city=" + encodeURIComponent( $(form.elements[ 'city' ]).val() ) +
			"&state=" + encodeURIComponent( $(form.elements[ 'state' ]).val() ) +
			"&zip=" + encodeURIComponent( $(form.elements[ 'zip' ]).val() );
	});

	return false;
}

//  SHOW SEARCH ERRORS
function showStoreSearchErrors( err ) {
	$('#search_error').html( err );
	$('#search_error_cnt').css( 'display', 'block' );
}

//  LOAD THE CITY & STATE OPTIONS ON THE RECIP PAGE.
function loadRecipCityState( load_city ) {

	el = document.getElementById( 'shipping_postal_code' );

	if( !( el.value.toString().length == 5 ) ) {
		return
	}

	$('#city_state_cnt').html( '<div class="zip_error">Searching...</div>' );

	url = "/order/city-state-from-zip/?zip=" + encodeURIComponent( $(el).val() );

	$.get(url, function(data){
		if( data == 'none' ) {
			$('#city_state_cnt').html( '<div class="zip_error">The zip code you entered is not valid.</div>' );
		} else {
			$('#city_state_cnt').html( data );

			// city?
			if( load_city != '' ) {
				loadPreSetCity( load_city );
			}
		}
	});
}

function loadPreSetCity( city ) {

	el = document.getElementById( 'shipping_city_select' );

	if( !( el && el.length > 0 ) ) {
		return;
	}

	for( var i = 0; i < el.length; i++ ) {
		if( el[i].value == city ) {
			el.selectedIndex = i;
		}
	}
}
