/**
 * Custom JS Functions
 */
 
// ** global variables ** //

/**
 * Product Browse dattributeid
 */
var pbDid = 969609;

/**
 * Create a shortcut to jQuery, calling no conflict due to our custom $ function
 * {@link http://docs.jquery.com/Using_jQuery_with_Other_Libraries}
 */
var $j = jQuery.noConflict();

/**
 * Function used to initialize our product browse functionality
 * @return string|int selected_did Optional
 */
function product_browse(selected_did) {
	//closes all accordion content divs
	$j('.product-browse-content').hide();

	if (!selected_did) {var selected_did = '';}
	var siteurl = ''

	$('content-browse').style.display = '';
	$('content').style.display = 'block';

	$('content-browse').innerHTML = '';
	write_product_browse_dd(pbDid, 'product-browse-list', siteurl, (selected_did != '' ? selected_did : ''));
}

/**
 * Function used to write out our product browse category list
 * @param {int} did
 * @param {string} divid
 * @param {string} siteurl
 * @param {string} selected_did Optional
 */
function write_product_browse_dd(did, divid, siteurl, selected_did) {
	if (!selected_did) {var selected_did = '';}
	var categories = '<ul>';

	var choices = list_children(did, 'pb');

	for (var i = 0, c_count = choices.length; i < c_count; i++) {
		var var_object = new Object();
			var_object.category = choices[i];
			var_object.siteurl = siteurl;
		
		categories += '<li>' +
		              ' <a id="product-browse-button-' + choices[i] + '" class="product-browse-button" href="javascript:;" onclick="show_product_browse_list(\'' + escape(json_encode(var_object)) + '\');">' + PBindex[choices[i]][1] + '</a>\n' +
		              ' <div id="product-browse-content-' + choices[i] + '" class="product-browse-content"><div class="clear"></div></div>' +
					  '</li>\n';
	}

	categories += '</ul>';
	$(divid).innerHTML = categories;

	if (selected_did != '') {
		//here we need to get our product list for this category
		var parameters = new Object();
			parameters._method = 'get_index_product_list';
			parameters.did = selected_did;

			AjaxRequest.post({
				'url': siteurl + 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': function(t) {write_product_browse_list(selected_did, siteurl, t.responseText);toggle_element('loading');},
				'onError': function(t) {alert('Unable to retrieve product(s) for this product type');toggle_element('loading');}
			});
	}
}

/**
 * Function used to write out our product browse list
 * @param {int} did
 * @param {string} divid
 * @param {string} siteurl
 * @param {object} product_data
 */
function write_product_browse_list(did, siteurl, product_data) {		
	var filename_array = window.location.pathname.split('/');
	var filename = filename_array[filename_array.length-2];

	var prod_list = "<ul id=\"" + did + "\">\n";

	if (product_data == "") {
		alert("No data available for the selected category. Please try your request again.");
		product_browse('');
		return;
	}

	//parse our json string
	product_data = json_decode(product_data);
	var products = product_data.products;

	for (var i = 0, product_count = products.length; i < product_count; i++) {
		if (filename == products[i].filename) {//on this product page, don't link and no mouseover event
			prod_list += '<li><a class=\"current\">' + products[i].productName + '</a></li>\n';
		} else {//not on product page, include mouseover and link
			prod_list += '<li><a href="' + siteurl + 'products/' + products[i].filename + '/?pbid=' + did + '">' + products[i].productName + '</a>' +
						 ' <ul>' +
						 '  <li>' + show_product(products[i].did, siteurl, json_encode(products[i])) + '</li>' +
						 ' </ul>' +
						 '</li>';
		}
	}

	prod_list += "</ul>\n<div class=\"clear\"></div>";

	$('product-browse-content-' + did).innerHTML = prod_list;

	//now we need to run our script to build our sub menus
	buildsubmenus(did);

	//if our menu is open, we're going to close it, else open it
	if ($j('#product-browse-content-' + did).is(':visible')) {
		$j('#product-browse-content-' + did).slideUp('normal');
	} else {
		$j('#product-browse-content-' + did).slideDown('normal');
	}
}

/**
 * Function used to display product selected by
 * user from our product browse list
 * @param {int} did
 * @param {string} siteurl
 * @param {object} product_data
 * @return {string} prod_div
 */
function show_product(did, siteurl, product_data) {
	if (product_data == "") {
		alert("No data available for the selected product. Please try your request again.");
		product_browse('');
		return;
	}
	
	//set our product_data (parsing our JSON string)
	var product_data = json_decode(unescape(product_data));

	//begin our product listing
	var prod_div = ' <div class="box rollover">';
		
	//product image
	if (product_data.productImage != '' && product_data.productImage != 'null') {
		prod_div += '  <img class="thumbnail float-left" alt="product image" src="' + siteurl + 'content/products/images/thumb/' + product_data.productImage + '" />';
	}

	prod_div += '  <div class="box-text float-left">';

	//product name
	if (product_data.realProductName != 'null') {
		prod_div += '  <h3>' + product_data.realProductName + '</h3>';
	}

	//subtitle
	if (product_data.subtitle != 'null') {
		prod_div += '  <h4>' + product_data.subtitle + '</h4>';
	}

	//description
	if (product_data.productDescription != 'null') {
		//prod_div += '  <p>' + truncate(product_data.productDescription, 250) + '</p>';
		prod_div += '  <p>' + product_data.productDescription + '</p>';
	}

	prod_div += '  <div class="clear"></div>';

	//end of content div
	prod_div += '  </div>';
	prod_div += '  <div class="clear"></div>';
	prod_div += ' </div>';

	return prod_div;
}
 
/**
 * Function used to build our submenus for our
 * product browse navigation menu
 * @param {string} menu_id
 * Original Code taken from {@link http://www.dynamicdrive.com/style/csslibrary/item/suckertree-menu-vertical/}
 */
function buildsubmenus(menu_id){
	var ultags = $(menu_id).getElementsByTagName('ul');

	for (var t = 0; t < ultags.length; t++) {
		if (ultags[t].parentNode.parentNode.id == menu_id) //if this is a first level submenu
			ultags[t].style.left=ultags[t].parentNode.offsetWidth + 'px'; //dynamically position first level submenus to be width of main menu item
		else //else if this is a sub level submenu (ul)
			ultags[t].style.left = ultags[t-1].getElementsByTagName('a')[0].offsetWidth + 'px'; //position menu to the right of menu item that activated it
			ultags[t].parentNode.onmouseover = function() {
				this.getElementsByTagName("ul")[0].style.display = 'block'
			}

		ultags[t].parentNode.onmouseout = function() {
			this.getElementsByTagName('ul')[0].style.display = 'none';
		}
	}

	for (var t = ultags.length-1; t >-1; t--) { //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
		ultags[t].style.visibility = 'visible';
		ultags[t].style.display = 'none';
	}
}

/**
 * Simple accordian style menu, for use with dual-lite product browse
 * @param string param_object
 * Original code taken from {@link http://www.stemkoski.com/stupid-simple-jquery-accordion-menu/}
 */
function show_product_browse_list(param_object) {		
	$j('div.product-browse-content').slideUp('normal');

	//set our param object for passing variables into our search product browse function
	var object = json_decode(unescape(param_object));

	//execute our search product browse function
	search_product_browse(object.category, object.siteurl);
}

/**
 * Function used to process our product browse
 * list item rollover functionality
 * @param {object} select_ref
 * @param {string} divid
 * @param {string} type
 * @param {string} siteurl
 * @param {string} attribute_search_history Optional
 */
function search_product_browse(category, siteurl) {	
	//don't process if they selected the top select list item ('all')
	if (category == pbDid) {
		$('product-browse-content-' + category).innerHTML = '';
	} else {
		//reset our div
		$('product-browse-content-' + category).innerHTML = '';

		var parameters = new Object();
			parameters._method = 'get_index_product_list';
			parameters.did = category;

			AjaxRequest.post({
					'url': siteurl + 'includes/ajax.php',
					'parameters': parameters,
					'onLoading': toggle_element('loading'),
					'onSuccess': function(t) {write_product_browse_list(category, siteurl, t.responseText);toggle_element('loading');},
					'onError': function(t) {alert('Unable to retrieve product(s) for this product type');toggle_element('loading');}
			});
	}
}

//-- QUICK SEARCH FUNCTIONS --//

function show_search_results(start, end) {
	var str_html = '';
	
	for (var i = start; i < end; i++) {
		str_html += '<div class="box">';
		str_html += '<img class="thumbnail float-left" src="content/products/' + results[i].productImage + '" alt="' + results[i].productName + '" />';
		str_html += '<div class="box-text float-left">';
		str_html += '<h3>' + results[i].productName + '</h3>';
		str_html += '<h4>' + results[i].subtitle + '</h3>';
		str_html += '<p>' + results[i].productDescription + '</p>';
		str_html += '<p><a href="' + results[i].filename + '">View Product Page</a></p>';
		str_html += '</div>';
		str_html += '<div class="clear"></div>';
		str_html += '</div>';
	}
	
	$('search-contents').innerHTML = str_html;	
}


/**
 * Function used to toggle our product browse/attribute search menu
 * @param {string} mode
 * @param {boolean} save Optional
 */
function toggle_menu(mode, save) {
	if (!save) {var save = false;}

	switch (mode) {
		case 'hide':
			if ($('side-pane')) {$('side-pane').style.display = 'none';}
			if ($('hide')) {$('hide').style.display = "none";}
			if ($('show')) {$('show').style.display = "";}	
			if ($('content')) {$('content').style.width = "auto";}
			if ($('content')) {$('content').style.paddingLeft = "0px";}
			if ($('map')) {$('map').style.width = "650px";}
			break;
		case 'show':
			if ($('side-pane')) {$('side-pane').style.display = 'block';}
			if ($('hide')) {$('hide').style.display = "";}
			if ($('show')) {$('show').style.display = "none";}
			if ($('content')) {$('content').style.width = "720px";}
			if ($('content')) {$('content').style.paddingLeft = "12px";}
			if ($('map')) {$('map').style.width = "420px";}			
			break;			
	}

	//update our cookie if applicable
	if (save) {
		save_product_browse_cookie(mode);
	}
}

//-- QUICK SEARCH FUNCTIONS --//

function show_search_results(start, end) {
	var str_html = '';
	
	for (var i = start; i < end; i++) {
		str_html += '<div class="box">';
		str_html += '<img class="thumbnail float-left" src="content/products/' + results[i].productImage + '" alt="' + results[i].productName + '" />';
		str_html += '<div class="box-text float-left">';
		str_html += '<h3>' + results[i].productName + '</h3>';
		str_html += '<h4>' + results[i].subtitle + '</h3>';
		str_html += '<p>' + results[i].productDescription + '</p>';
		str_html += '<p><a href="' + results[i].filename + '">View Product Page</a></p>';
		str_html += '</div>';
		str_html += '<div class="clear"></div>';
		str_html += '</div>';
	}
	
	$('search-contents').innerHTML = str_html;	
}

/**
 * Truncates a string to given length and appends suffix to it (indicating that it is only an excerpt).
 * Original Code taken from {@link http://api.prototypejs.org/language/string/prototype/truncate/}
 */
function truncate(string, length) {
	length = length || 30;
	truncation = '...';
	return string.length > length ?
	  string.slice(0, length - truncation.length) + truncation : String(string);
}

//-- SHOPPING CART FUNCTIONS --//

/**
 * Function used to add/update item in shopping cart. Checks to ensure
 * item isn't already in the cart, if so update routine runs
 * @param {integer} item_id
 */
function add_to_cart(item_id) {
	var total_items = $('total_items').value;
	var new_item_id = (parseInt(total_items) + 1);
	var item_name = ($('product_name_' + item_id) ? $('product_name_' + item_id).innerHTML : '');
	var item_description = $('product_description_' + item_id).innerHTML;
	var item_quantity = $('product_quantity_' + item_id).value;
	var item_price = ($('product_price_' + item_id).value / 100);
	var item_size = ($('product_size_' + item_id) ? $('product_size_' + item_id).value : '');
	var item_color = ($('product_color_' + item_id) ? $('product_color_' + item_id).value : '');

	if (item_quantity == '') {
		alert('Please enter a quantity for item: ' + item_name);
		return;
	}

	if ($('item_id_' + item_id + (item_size != '' ? '_' + item_size : '') + (item_color != '' ? '_' + item_color : ''))) {
		//item exists in cart already, update
		update_cart(item_id, $('item_id_' + item_id + (item_size != '' ? '_' + item_size : '') + (item_color != '' ? '_' + item_color : '')).value, item_quantity);
	} else {
		//item doesn't exist, add
		var row = build_shopping_cart_row(new_item_id, item_id, item_quantity, item_price, item_name, item_description, item_size, item_color);
		var target_element = $(total_items == 0 ? 'cart_header' : 'cart_item_' + total_items); //determine where to add
		var next = target_element.nextSibling;
		(next) ? target_element.parentNode.insertBefore(row, next) : target_element.parentNode.appendChild(row);
		
		//update total items in cart
		$('total_items').value = (parseInt(total_items)+parseInt(1));
		
		//update cart subtotal
		update_cart_subtotal();
	}

	//clear out our quantity
	$('product_quantity_' + item_id).value = '';

	//reset our size if applicable
	if (item_size != '') {
			$('product_size_' + item_id).selectedIndex = 0;
	}
	
	//reset our color if applicable
	if (item_color != '') {
			$('product_color_' + item_id).selectedIndex = 0;
	}

	//scroll to our shopping cart details
	scroll_to('cart-details');
}

/**
 * Function to build our elements for a new shopping cart row
 * @param {integer} new_item_id
 * @param {integer} item_id
 * @param {integer} item_quantity
 * @param {string} item_price
 * @param {string} item_name Optional
 * @param {string} item_description
 * @param {string} item_size
 * @param {string} item_color
 * @return {object} row
 */
function build_shopping_cart_row(new_item_id, item_id, item_quantity, item_price, item_name, item_description, item_size, item_color) {
	//Robin: "Holy Shit Batman! All this just to build our table row client side!!!"
	var row = '';
	var cell = '';
	var attribute = '';
	var link_node = '';
	var input = '';
	var image = '';
	row = document.createElement('tr');
	row.setAttribute('id', 'cart_item_' + new_item_id);
	row.setAttribute('class', 'cart-content');

	cell = document.createElement('td');
	cell.setAttribute('height', '30');

	link_node = document.createElement('a');
	link_node.setAttribute('href', 'javascript:void(0);');
	link_node.setAttribute('onclick', "scroll_to('product_" + item_id + "');");
	link_node.appendChild(document.createTextNode((item_name != '' ? item_name : item_description) + (item_size != '' ? ' (' + item_size + ')' : '') + (item_color != '' ? ' (' + item_color + ')' : '')));
	cell.appendChild(link_node);
	row.appendChild(cell);

	cell = document.createElement('td');
	cell.setAttribute('align', 'left');
	cell.setAttribute('height', '30');
	cell.appendChild(document.createTextNode(format_currency(item_price)));
	row.appendChild(cell);

	cell = document.createElement('td');
	cell.setAttribute('height', '30');

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_id_' + item_id + (item_size != '' ? '_' + item_size : ''));
	input.setAttribute('name', 'item_id_' + item_id + (item_size != '' ? '_' + item_size : ''));
	input.setAttribute('value', new_item_id);
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_name_' + new_item_id);
	input.setAttribute('name', 'item_name_' + new_item_id);
	input.setAttribute('value', (item_name != '' ? item_name : item_description));
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_description_' + new_item_id);
	input.setAttribute('name', 'item_description_' + new_item_id);
	input.setAttribute('value', ((item_name != '') ? item_name : item_description) + (item_size != '' ? ' (' + item_size + ')' : '') + (item_color != '' ? ' (' + item_color + ')' : ''));
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_quantity_' + new_item_id);
	input.setAttribute('name', 'item_quantity_' + new_item_id);
	input.setAttribute('value', item_quantity);
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_price_' + new_item_id);
	input.setAttribute('name', 'item_price_' + new_item_id);
	input.setAttribute('value', item_price);
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'text');
	input.setAttribute('id', 'cart_item_quantity_' + new_item_id);
	input.setAttribute('name', 'cart_item_quantity_' + new_item_id);
	input.setAttribute('value', item_quantity);
	input.setAttribute('size', '1');
	input.setAttribute('onchange', 'if(validate_quantity(this, true)){update_cart(' + item_id + ', ' + new_item_id + ', this.value, true);}');
	cell.appendChild(input);
	row.appendChild(cell);
	
	cell = document.createElement('td');
	cell.setAttribute('align', 'left');
	cell.setAttribute('height', '30');
	cell.setAttribute('id', 'cart_item_price_' + new_item_id);		
	cell.appendChild(document.createTextNode(format_currency(parseFloat(item_price) * parseInt(item_quantity))));
		
	row.appendChild(cell);

	cell = document.createElement('td');
	cell.setAttribute('height', '30');
	cell.setAttribute('align', 'center');

	image = document.createElement('img');
	image.setAttribute('src', 'images/merchandise-delete-icon.jpg');
	image.setAttribute('alt', 'Delete Item');
	
	link_node = document.createElement('a');
	link_node.setAttribute('href', 'javascript:remove_from_cart(' + new_item_id + ');');
	link_node.setAttribute('class', 'remove');
	link_node.appendChild(image);
	cell.appendChild(link_node);
	row.appendChild(cell);
	
	return row;
}

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 3/9/2009
 * @author Ariel Flesler
 * @version 1.4.1
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

