/**
 * Custom JS Functions
 */
 
// ** global variables ** //

/**
 * Product Browse dattributeid
 */
var pbDid = 889142;

/**
 * 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();

/**
 * 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 = '<br />';
	
	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);
	}
}

function compare_products() {
	//make sure at least two products are selected
	if($j('#product-table input:checkbox:checked').length < 2) {
		alert('You must select two or more products to compare');
		return false;
	} else {
		//hide any rows that are not selected
		$j('#product-table input:checkbox:not(:checked)').each(function() {
			$j(this).parents('tr.product-row').hide();
		});
	}
}

function tab_content(tab) {
	$j('div.product-content div').hide();
	$j('#' + tab).show();
}

function product_index_ies_content(clicked_link, did) {
	$j('#ies-content').remove();
	
	var parent_row = $j(clicked_link).parents('tr.product-row');
	parent_row.after('<tr><td id="ies-content" colspan="12"></td></tr>');
	get_ies(did, true);
}

function ies_index_content(clicked_link, did) {
	$j('#ies-content-' + did).remove();
	var parent_row = $j(clicked_link).parents('tr.category-row');
	parent_row.after('<tr class="no-column-borders"><td id="ies-content-' + did + '" colspan="3"></td></tr>');
	get_category_ies(did);
}

function get_category_ies(did) {
	var parameters = new Object();
	parameters._method = 'get_ies';
	parameters.dattributeid = did;
	parameters.type = 'category';
	
	var success = function(t) {
		$j('#ies-content-' + did).empty();
		$j('#ies-content-' + did).append('<div class="close-button"><a href="javascript:;" onclick="$j(\'#ies-content-' + did + '\').remove();">Close</a></div>');
		$j('#ies-content-' + did).append(t.responseText);
		toggle_element('loading');
	}
	
	AjaxRequest.post({
		'url': 'includes/ajax.php',
		'parameters': parameters,
		'onLoading': toggle_element('loading'),
		'onSuccess': success, 
		'onError': function(t) {alert('Unable to retrieve IES data');toggle_element('loading');}
	});
}

function get_ies(dattributeid, close_link) {
	var parameters = new Object();
	parameters._method = 'get_ies';
	parameters.dattributeid = dattributeid;
	parameters.type = 'product';
	
	var success = function(t) {
		$j('#ies-content').empty();
		if (close_link) {
			$j('#ies-content').append('<div class="close-button"><a href="javascript:;" onclick="$j(\'#ies-content\').remove();">Close</a></div>');
		}
		$j('#ies-content').append(t.responseText);
		toggle_element('loading');
	}
	
	AjaxRequest.post({
		'url': 'includes/ajax.php',
		'parameters': parameters,
		'onLoading': toggle_element('loading'),
		'onSuccess': success, 
		'onError': function(t) {alert('Unable to retrieve IES data');toggle_element('loading');}
	});
}

function toggle_related_products() {
	$j('a.toggle-related-products').children().toggle('250');
	$j('li.extra-related-products').toggle('250');
}

/**
 * Function loads our Google maps script dynamically
 */
function load_maps_script() {
	var m_script = document.createElement("script");
	m_script.type = "text/javascript";
	m_script.src = "http://maps.google.com/maps?file=api&v=2.x&key=" + gkey + "&async=2&callback=load_directions_map";
	document.body.appendChild(m_script);
}

/**
 *  Load our distributor map based off search results written to our page as js code (json variables)
 */
function load_directions_map() {
	//var directions_location='{"latitude"-74.0174420:,"longitude":40.9822440,"tolerance":25}';
	
	if (GBrowserIsCompatible()) {
		var map = new GMap2($("map"));
		var point = new GLatLng(40.9822440,-74.0174420);
		map.addControl(new GSmallZoomControl3D());
		map.addControl(new GScaleControl());
		map.setCenter(point);
		map.setZoom(14);
		
		var marker = new GMarker(point);
		var html = '<div><h4>Kurt Versen</h4><p>10 Charles Street<br />Westwood, NJ 07675<br /><a href="http://maps.google.com/maps?daddr=10+Charles+Street+Westwood+NJ+07675" target="_blank">Get Directions from Google Maps</a></p>';
		/*GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html, {maxWidth:150});
		});*/
		marker.openInfoWindowHtml(html, {maxWidth:150});
		
		map.addOverlay(marker);
	}
}

