/**
 * Custom JS Functions
 */
 
// ** global variables ** //

/**
 * Product Browse dattributeid
 */
var pbDid = 884351;

/**
 * Attribute Search dattributeid
 */
//var asDid = 405308;

/**
 * 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();

$j(document).ready(function() {
    $j('ul.product-listing li').hover(function() {
		$j(this).animate({top: '+=8'}, 300);					
	},function() {
		$j(this).animate({top: '-=8'}, 300);				
	});
});

/**
 * 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>' + 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;	
}

//-- 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 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 nextdiv = next_div('prod-browse', divid);
			 
	var categories = '';
	
	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 += '<div id="prod-browse-button-' + choices[i] + '" class="accordion-button" onclick="show_product_browse_list(\'' + escape(json_encode(var_object)) + '\');"><span class="light">' + PBindex[choices[i]][1] + '</span></div>\n' +
		              '<div id="prod-browse-content-' + choices[i] + '" class="accordion-content"><div class="clear"></div></div>\n';
	}

	categories += '<div id="' + nextdiv + '"></div>';
	$(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 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) {		
		$('prod-browse-content-' + category).innerHTML = '';
	} else {
		//reset our div
		$('prod-browse-content-' + category).innerHTML = '';

		//if this is a non-product link, open a new window with our url
		if (PBindex[category][0] == "Non-Product Link") {
			//reset our category list?
			//open our window
			window.open(PBindex[category][2]);					
			return;
		} else {
			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');}
				});
		}
	}
}

/**
 * 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 + "\" class=\"side-nav\">\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>";

	$('prod-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('#prod-browse-content-' + did).is(':visible')) {
		$j('#prod-browse-content-' + did).slideUp('normal');
	} else {
		$j('#prod-browse-content-' + did).slideDown('normal');
	}
}

/**
 * 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("div.accordion-content").hide();
	
	if (!selected_did) {var selected_did = '';}	
	var siteurl = '' 

	$('content-browse').style.display = '';
	$('content').style.display = 'block';

	var ulstring = ' <ul>' +
				   '  <li><a href="javascript: void(0);" onclick="attribute_search();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/attribute_search/\');' : '') + '"><span>Attribute Search</span></a></li>' +
				   '  <li class="selected"><a href="javascript: void(0);" onclick="product_browse();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/product_browse/\');' : '') + '"><span>Product Browse</span></a></li>' +
				   ' </ul>' +
				   ' <div class="clear"></div>';

	/*$('pbrowse-tabs').innerHTML = ulstring;	*/
	$('content-browse').innerHTML = '';
	/*$('bottomDiv').innerHTML = '';*/
	/*$('attSearch1').innerHTML = ''; */
	$('prod-browse').innerHTML = '';
	/*$('attSearch1').style.display = 'none';*/

	write_product_browse_dd(pbDid, 'prod-browse', siteurl, (selected_did != '' ? selected_did : ''));
	
	$('prod-browse').style.display = '';
}

/**
 * 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.accordion-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 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';
	}
}

/**
 * Function to initialize our attribute search functionality
 * @param {string} attribute_search_history Optional
 */
function attribute_search(attribute_search_history) {
	if (!attribute_search_history) {var attribute_search_history = '';}
	var siteurl = ''; 
	
	$('content-browse').style.display = 'none';
	$('content').style.display = 'block';
				   
	var ulstring = ' <ul>' +
				   '  <li class="selected"><a href="javascript: void(0);" onclick="attribute_search();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/attribute_search/\');' : '') + '"><span>Attribute Search</span></a></li>' +
				   '  <li><a href="javascript: void(0);" onclick="product_browse();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/product_browse/\');' : '') + '"><span>Product Browse</span></a></li>' +
				   ' </ul>';

	$('pbrowse-tabs').innerHTML = ulstring;

	$('content-browse').innerHTML = '';
	$('attSearch1').innerHTML = ''; //clear existing att search
	
	$('content-browse').style.display = 'none';
	$('attSearch1').style.display = 'block';
	$("prod-browse").innerHTML = ''; //clear any existing product list
	$("prod-browse").style.display = 'none';

	if (attribute_search_history != '') {
		write_attribute_search_dd(asDid, 'attSearch1', siteurl, attribute_search_history, attribute_search_history);
	} else {
		write_attribute_search_dd(asDid, 'attSearch1', siteurl);
	}
}

//-- FILE SEARCH FUNCTIONS --//

/**
 * Function used to show our given div, also hides
 * other divs and sets active nav link (used by our
 * download pages e.g. instruction sheets, photomotry, etc.)
 * @param {string} div
 */
function show_div(div) {
	var nav_array = $('products-nav').getElementsByTagName('a'), div_array = $('products-container').getElementsByTagName('div');

	//reset our other nav links
	for (var i = 0, nav_length = nav_array.length; i < nav_length; i++) {
		nav_array[i].className = '';
	}

	//hide all our other divs
	for (i = 0, div_length = div_array.length; i < div_length; i++) {
		if (div_array[i].id != '') {
			div_array[i].style.display = "none";
		}
	}

	//clear out our file-search-results (where applicable)
	if ($('file-search-results')) {
		$('keywords').value = '';
		$('file-search-results').innerHTML = '';
		$('file-search-results').style.display = "none";
	}
	
	//attempt to show our div and set our current link
	if ($(div)) {
		//set our active nav link
		$('nav-' + div).className = "current";

		//show our div
		$(div).style.display = "block";
	}

	return;
}

/**
 * Function used to search our files, based on the entered keyword(s)
 * @param {string} filetype
 */
function search_files(filetype) {
	var nav_array = $('products-nav').getElementsByTagName('a'), div_array = $('products-container').getElementsByTagName('div'), keywords = $('keywords').value;

	//reset our other nav links
	for (var i = 0, nav_length = nav_array.length; i < nav_length; i++) {
		nav_array[i].className = '';
	}

	//hide all our other divs
	for (i = 0, div_length = div_array.length; i < div_length; i++) {
		if (div_array[i].id != '') {
			div_array[i].style.display = "none";
		}
	}
	
	if (keywords != '' && filetype != '') {
		var failure = function(t) {alert('Unable to process your search.');toggle_element('loading');}
		var success = function(t) {$('file-search-results').innerHTML = (t.responseText == '') ? 'No results found for ' + keywords + '.' : t.responseText;toggle_element('loading');}

		var parameters = new Object();
		parameters._method = 'search_files';
		parameters.filetype = filetype;
		parameters.keywords = keywords;
		
		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});
	}
}

/**
 * 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-bar')) {$('side-bar').style.display = 'none';}
			if ($('hide')) {$('hide').style.display = "none";}
			if ($('show')) {$('show').style.display = "";}	
			break;
		case 'show':
			if ($('side-bar')) {$('side-bar').style.display = 'block';}
			if ($('hide')) {$('hide').style.display = "";}
			if ($('show')) {$('show').style.display = "none";}

			break;			
	}

	//update our cookie if applicable
	if (save) {
		save_product_browse_cookie(mode);
	}
}


/**
 * @author Stéphane Roucheray 
 * @extends jquery
 */


jQuery.fn.carousel = function(previous, next, options){
	var sliderList = jQuery(this).children()[0];
	
	if (sliderList) {
		var increment = jQuery(sliderList).children().outerWidth("true"),
		elmnts = jQuery(sliderList).children(),
		numElmts = elmnts.length,
		sizeFirstElmnt = increment,
		shownInViewport = Math.round(jQuery(this).width() / sizeFirstElmnt),
		firstElementOnViewPort = 1,
		isAnimating = false;
		
		for (i = 0; i < shownInViewport; i++) {
			jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment + increment + "px");
			jQuery(sliderList).append(jQuery(elmnts[i]).clone());
		}
		
		jQuery(previous).click(function(event){
			if (!isAnimating) {
				if (firstElementOnViewPort == 1) {
					jQuery(sliderList).css('left', "-" + numElmts * sizeFirstElmnt + "px");
					firstElementOnViewPort = numElmts;
				}
				else {
					firstElementOnViewPort--;
				}
				
				jQuery(sliderList).animate({
					left: "+=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){isAnimating = false;});
				isAnimating = true;
			}
			
		});
		
		jQuery(next).click(function(event){
			if (!isAnimating) {
				if (firstElementOnViewPort > numElmts) {
					firstElementOnViewPort = 2;
					jQuery(sliderList).css('left', "0px");
				}
				else {
					firstElementOnViewPort++;
				}
				jQuery(sliderList).animate({
					left: "-=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){isAnimating = false;});
				isAnimating = true;
			}
		});
	}
};


