
//JQUERY TRIGGER
jQuery(document).ready(function() {

//-------===== set up globals and do opening stuff ========----------//
var thum_array = [];
var main_array = [];
var current_content = '';
var current_products = [];//json.descriptions
var current_brand_details = []; //json brand shit
var wanted_ids = [];
var imagebar_width = 0;
var tech_swap = '';
var auto_fox = 0;//have I already made an auto-selection for you?
var hash_b = '$';
var hash_t = '@';
var hash_s = '';
var incoming_selection = '';
var latest_item ='';
var current_shot = 0;
var hashing = 0;


var type_array = ["Phono Stage", "Turntable","Cartridge","Tonearm","CD/SACD","DAC","Music Server","Integrated Amplifier","Pre-Amp","Power Amp","Multi-Channel Amplifier","Floorstanding Loudspeaker","Standmount Loudspeaker","Subwoofer","Speaker stand","Audio Cable","Interconnect","Mains","Isolation Rack"];

var type_array_shorthand = ["Phono Stage", "Turntable","Cartridge","Tonearm","CD/SACD","DAC","Music Server","Integrated","Pre-Amp","Power Amp","Multi-channel","Floorstander","Standmount","Sub","Stand","Cable","Interconnect","Mains","Rack"];

var brand_array = [ 'artora' , 'audioanalogue', 'BCD', 'bow', 'brinkmann', 'burmester', 'diapason', 'esoteric', 'finite', 'grand', 'gryphon', 'JPS', 'keithmonks', 'levinson', 'michell', 'pathos', 'primare', 'proac', 'revel', 'simonyorke', 'SME', 'sumiko', 'sys', 'tannoy', 'track', 'triangle', 'unison', 'vac', 'zingali'];




//-------===== set up globals and do opening stuff ========----------//


	//---GETS THE BALL ROLLING EITHER WITH LINK IN OR BASE SET UP--------//
				//do_media_detection();
	var linked_in = check_hash();
	
		if(linked_in === 1){
			update_from_hash();
				}else{
			load_home();
			//build_home_strip();
			load_with_delay();
			}








//---------------------MANAGE COLOUR CHANGE ON THE TABS-------------------//
$('.tab').click(function (){ 
	hashing =0;
	var sl = this.id;
	var s = "#" + sl;
		set_button_as_on(s);
		update_hash();
		});


$('.btab').click(function (){
	//tog allows only one brand at a time
	var tog = "off";
		hashing =0;
		update_selection('');
	
	if($(this).attr('name') == 'on'){
	tog = 'on';
	}
	
	//changed swith off all and remove styles
	$('.btab').attr("name", "off");
	$('.btab').removeAttr("style");
		
	//then style the clicked button
	var sl = this.id;
	var s = "#" + sl;
	if(tog == 'off'){
		set_button_as_on(s);		
		}
		update_hash();
		update_selection('');		
	});



function set_button_as_on(b_id){
//////console.log("BID just on: " + b_id);
	if($(b_id).attr("name") == "off"){
			 $(b_id).css('background-color', 'rgb(166,27,27)');
			 	$(b_id).attr("name","on");
			 		}else{
			 	$(b_id).removeAttr("style");
			$(b_id).attr("name","off");
						}
					
					}
				
				
function set_button_as_on_forsure(b_id){
		//////console.log("BID for sure: " + b_id);
			 $(b_id).css('background-color', 'rgb(166,27,27)');
			 	$(b_id).attr("name","on");
			 	}

			
					
$('#brand_drop').live('click', function() {
						
						var l = $(this).offset();
						////alert("L: " + l.left);
						$('#select2').css("left", l.left);
						$('#select2').toggle();
						});							
					
					
$('#component_drop').live('click', function() {
						////alert("YEP");
						
						var l = $(this).offset();
						////alert("L: " + l.left);
						$('#select1').css("left", l.left);
						$('#select1').toggle();
						});		
						

$('html').click(function() {
 var t = $('#select1').css("display");
 var b = $('#select2').css("display");
 ////alert(t);
	if(t!= 'none'){
	$('#select1').toggle();
	}
	
	if(b!= 'none'){
	$('#select2').toggle();
	}
	
	
 });

 $('#select1').click(function(event){
     event.stopPropagation();
 });					
 $('#select2').click(function(event){
     event.stopPropagation();
 });						
					

					
//---------------------MANAGE COLOUR CHANGE ON THE TABS-------------------//			
$('#leftarrow').live('mouseover', function() {
				if($('#images').width() > 860){
					$(this).removeClass();
						$(this).addClass("transparent_2");
							}
						});

$('#rightarrow').live('mouseover', function() {
				if($('#images').width() > 860){
					$(this).removeClass();
						$(this).addClass("transparent_2");
							}
						});
				
				
$('#leftarrow, #rightarrow').live('mouseout', function() {
				if($('#images').width() > 860){
					$(this).removeClass();
						$(this).addClass("transparent_1");
							}
						});

$('#images').live('change', function() {
				var y = $('#images').css("margin-left");
				var i = y.slice(0,(y.length)-2);
					if(i>=0){
						$(this).addClass("transparent_0");
							}
						});


$('.dot').live('mouseover', function() {
					if($(this).attr('alt') == 'off'){
						$(this).removeClass("transparent_2");
						$(this).addClass("transparent_6");
						}
						});	

$('.dot').live('mouseout', function() {
					if($(this).attr('alt') == 'off'){
						$(this).removeClass("transparent_6");
						$(this).addClass("transparent_2");
						}
						});	
						
						
$('.dot').live('click', function() {

					$('.dot').each(function(){
					
					if($(this).attr('alt') == 'on'  )
					$(this).addClass("transparent_2");
					});
					
					$('.dot').attr('alt', 'off');
					$(this).attr('alt', 'on');
					$(this).removeClass();
					$(this).addClass('dot');
						
						
					var shift = $(this).attr('id');
						shift = parseInt(shift.substring(2));
					var x = $('#images').css("width");


					var total_width = x.slice(0,(x.length)-2);//width as number
					var differance = 820 - total_width;
				
					var l = shift*820;
					if(l>(total_width-820)){l = total_width-820;}
					
					var move = "-" + l.toString() + "px";
					
					 	$('#images').animate({
								marginLeft: move
									}, 100);
					 	
					 	
						});	



	function add_dots(n){
	
	var dot_string = '';
	
	if(n>1){
	
	dot_string = '<div class="sphere_box"><img class="dot" id="d_0" src="images/t_dot.png" alt="on"/></div>';
	
	for(var x=1; x<n; x++){
	
	dot_string += '<div class="sphere_box"><img class="dot transparent_2"  id=d_' + x + ' src="images/t_dot.png" alt="off"/></div>';
											
			}
			
			$('#inner_box').css("width", n*30);
			
	var dot_holder = document.getElementById("inner_box");
		dot_holder.innerHTML = dot_string;
		}
	}
			
			
			

//----------------------HANDLE MOVING THE IMAGE STRIP----------------------------//
$('#leftarrow').live('click', function() {
				
				var x = $('#images').css("width");
				var y = $('#images').css("margin-left");
				var margin_left = y.slice(0,(y.length)-2);//m-left as number
				var total_width = x.slice(0,(x.length)-2);//width as number
				var differance = total_width - 840;
			
					if(differance > 0 && margin_left <0){
						if(Number(margin_left) + 200 < 0){
							$('#images').animate({
								marginLeft: "+=200px"
									}, 100);
								}else {
							$('#images').animate({
						marginLeft:  "0px"
					}, 100);
				}
			}
			verify_dots(total_width);
		});		
		
		
function verify_dots(w){

		var y = $('#images').css("margin-left");
		var margin_left = y.slice(0,(y.length)-2);
		var ml_num = Number(margin_left) - 200;//m-left as number
		var dot_num = Math.ceil(ml_num/800); 
		var dot_count = Math.ceil(w/820)-1; 
		var edge_condition = w - 820;

	if(ml_num <= -edge_condition){
		var dot_name = '#d_' + dot_count; 
		}else{
	 	var dot_name = '#d_' + dot_num*-1;
	}

			$('.dot').each(function(){
			$(this).attr('alt', 'off');
			
			if($(this).hasClass("transparent_2") == false){
			$(this).addClass('transparent_2');
			}
			});
					
			$(dot_name).attr('alt', 'on');
			$(dot_name).removeClass('transparent_2');
				
}







$('#rightarrow').live('click', function() {
				
				var x = $('#images').css("width");
				var y = $('#images').css("margin-left");
				var margin_left = y.slice(0,(y.length)-2);//m-left as number
				var total_width = x.slice(0,(x.length)-2);//width as number
				var differance = 840 - total_width;
					
					if(differance<0 && Number(margin_left) > differance){
						if((Number(margin_left) - 200) > differance){
							$('#images').animate({
								marginLeft: "-=200px"
									}, 100);
								}else {
							var set_x = differance.toString() +'px';
						$('#images').animate({
					marginLeft: set_x
						}, 100);
					}
				}
				
				verify_dots(total_width);
			});		






$('.thumbs a').click(function() {
    var bigImage = $(this).attr('href');
    	$('#primeContainer').fadeOut('fast', function() {
        	$('#largeImg').attr('src', bigImage);
        		$(this).fadeIn('fast');
    				});
    				return false;
						});					
					
					
					

//----------------------HANDLE IMAGE STRIP CLICKS TO UPDATE MAIN IMAGE----------------------------//
//----------also needs to load additional images and pepare slide show if relevant--------------//
$('.thumbnail').live('mouseup', function() {
	hashing=0;
	//update_selection('s' + this.id);
	do_thumb_click(this.id);
				});//---------------- end thumbnail to main image update listener -----------------//
													


								
							
function do_thumb_click(pid){

					auto_fox=1;//don't auto-select from now on.
					
					var a = $('#' + pid).attr("src"); 
					
					if(a){
					//if this was a genuine click event update hash to reflect state
					
						update_selection('s' + pid);
						
					
					var t = "#" + pid;
					
					//deal with a being undefined...?
					a = a.substr(0, (a.length)-6) + '.jpg';
				
					var deets_box_id = "#im_" + pid;
						
					//reset deets bg and text
					$('.im').css("background-color", 'rgb(237,238,239)');
					$('.im_info_b').css("font-weight", '100');
					$('.im_info_b').css("color", 'rgb(53,53,53)');
					
					
						//highlight in-play
						$(t).parent().css("background-color", 'rgb(53,53,53)');
						$(t).next().css("color", 'rgb(250,251,252)');
						$(deets_box_id).css("font-weight", '500');
								
								
						var u = 'url("' + a + '")';
							var bgImg = new Image();
								bgImg.src = a;
									bgImg.onload = function(){
   										$("#image_zero").fadeOut('slow', function() {
   										$('#content').css("margin-left", 0);
   										$('.ext_shot').remove();
   									$("#input").empty();

        						$("#image_zero").attr("src", a).fadeIn(1000, function() {
        					var prod = get_product_info(pid);
        						latest_item = prod;
        							current_shot = 0;
        								window.document.title = latest_item.brand + " " + latest_item.name;
        								
        						prepare_shots();
        						//console.log("DTC");
        							get_prod_html(prod);
               							if(prod.images != null && prod.images.length>1)
               								{
               								var w =  prod.images.length * 1021;
        										$('#content').css("width", w);
               										$('.right_slider').fadeIn();
               											}else{
               											$('#content').css("width", 1000);
               												$('.right_slider').fadeOut();
               													$('.left_slider').fadeOut();
               														}
        														});
															});
														};
													}else{
													//problem of some kind, hit the first thumbnail
													first_thumb("thumbclick");
													}
												}							



function update_selection(sel){
hash_s = sel;
location.hash = hash_b + '/' + hash_t + '/' + sel;
}

					
											
											
//actually needs to get all shots
function prepare_shots(){
if(latest_item != ''){
		for(var s=1; s<latest_item.images.length; s++){
			var sss = new Image();
				sss.className = "ext_shot";
					sss.src = "images/components/" + latest_item.short + "/" + latest_item.images[s];
							$('#content').append(sss);
							}
						}
					}
																			
											



//----------------  ARTICULATE THE MAIN IMAGE -----------------//
$('.right_slider').live('mouseup', function() {		

if($('.left_slider').css('display') == 'none'){
$('.left_slider').fadeIn();
}

$("#input").animate({
   marginLeft: "-420px"
  }, 1000, 'easeOutCirc', function() {
    // Animation complete. Add info tab
    
    var x=document.getElementById("tabbed_input");
    
	if(!x){
  		var info_tab = document.createElement('div');
  			info_tab.id = "tabbed_input";
				info_tab.className='tabbed';		
					$("#content_holder").prepend(info_tab);
						}
  							});
  			
	
  					

  	  						
				//////alert("CURRENT: " + current_shot);
  				if(current_shot<latest_item.images.length-1 && latest_item.images.length>1){		
			$('#content').animate({
		marginLeft: "-=1000px"
	}, 1000,'easeOutCirc');
		current_shot++;
			//prepare_shots();
				}
					});				
											


$('.left_slider').live('mouseup', function() {		
	if(current_shot>0){		
			$('#content').animate({
		marginLeft: "+=1000px"
	}, 1000,'easeOutCirc');
		current_shot--;
				}
					});	








			
									
										
function get_product_info(p_n){
for(var i=0; i<current_products.length; i++){
	if(current_products[i].id == p_n){
		return current_products[i];
			}else{
			//do nowt
			}
				}
				return 0;
					}





function get_prod_html(prod){
		var str = '';
		var arrow = '<div class="lnk" ><img src="images/small_round.gif" /></div>';

			//----=== if we have a product review do the layout for that ====----//	
	if(prod.reviews != null){
			str+= '<div class="rev">';
		var revs = [];
					
			for(var i=0; i<prod.reviews.length; i++){
			str += '<div class="rb">';
					 	
	if(prod.reviews[i].qintro.length>0){
			str += '<div class="intro">' + prod.reviews[i].qintro + '</div>';
					 					}
					 						
	if(prod.reviews[i].qlink.length>8){
	////alert("YO: " + prod.reviews[i].qlink.length);
			str += '<a href="' + prod.reviews[i].qlink +'" target="_blank">';
										}
									
			str += '<div class="big_quote left"><div class="inner_quote">\u201c</div></div><div class="quote">';
			str += prod.reviews[i].quote + '<div class="BQ">\u201d</div></div><div class="attr">';
								
	if(prod.reviews[i].qlink.length>8){
			str += arrow;
										}
			str += '<div class="attr_w">';
			str += prod.reviews[i].qattr + '</div></div>';
	if(prod.reviews[i].qlink.length>8){
			str += '</a>';
	if(prod.reviews[i].qintro.length>0){
			str += '<br/><br/>';
					 					}
									}
			str += '</div>';
									}
			str += '</div>';	
								}
														
		var top_line = '<div class="info_wrapper"><div class="brandname">'+ prod.brand;
			top_line += '</div> <div class="productname"> ' + prod.name + '</div> <div class="ptype">' + prod.type + '</div><br/>';
						
		var product_info =  prod.text + '<br/>'+ str +'<br/><br/></div>';
		var close = '<div class="close"></div>';
 		var more_links = '<div class="more"> <a href="' + prod.url + '" target="_blank"> manufacturer </a></div><div class="tech"> tech </div> ';
 		var tech_links = '<div class="more"> <a href="' + prod.url + '" target="_blank"> manufacturer </a></div><div class="back"> back </div>';
		var tech_deets = '<div class="td">' +prod.tech + '</div><br/><br/></div>';								
		var info = close + top_line + product_info + more_links;
	
		
		$("#input").html(info);
			current_content = info;
				tech_swap =  close + top_line + tech_deets + tech_links;										}

		$('.tech').live('mouseup', function() {
		$("#input").html(tech_swap);	
						});
					
		$('.back').live('mouseup', function(e) {
		$("#input").html(current_content);
						});//ENDS GET HTML





		//----------------HANDLE INFO BOX HIDE/SHOW-------------------//					
		$('.close').live('mouseup', function() {
		//if brand only, when tab is closed, select first item in thumb list
		var currently_on = $('.tab[name="on"]');
		var currently_on_b = $('.btab[name="on"]');
		
				if((currently_on > 0 | currently_on_b > 0) && auto_fox==0 ){
				first_thumb("close");
				}animate_info_out();
  											});	
	
	
	
	function first_thumb(a){
	//////console.log("FT: " + a);
	if(auto_fox == 0){
			auto_fox = 1;
				var xxxxxx = $('.thumbnail:first');
				var yyyyyy = $('.roomnail:first');
				//////////////////console.log("RN: " + xxxxxx.attr("id"));
					if(yyyyyy.attr("id")){
					////////console.log("yyyyyy!" );
						do_thumb_click(yyyyyy.attr("id"));
							}else{
							////////console.log("yyyyyy!" );
								do_thumb_click(xxxxxx.attr("id"));
									}
										}
									
									}
	
	



		//return info from tabbed info bar
		$('#tabbed_input').live('mouseup', function() {
			animate_info_in();
  					});		
						
						
		//---------- USED to replace home/about us when there's no content selected ----------------/
	function load_home(){
	//console.log("HOME");
var info = '<div class="close"></div><div class="info_wrapper"><div id="headsup"><span class="component" style="font-style:italic;">Welcome to <b class="light">The Music Room</b></span><br /><br />The Music Room first opened its doors in 1979 and this fresh innovative approach reflects our belief that it is our current era that is setting ever more exciting standards for high-end audio. Our stock is extensive to say the least, and this website is designed to allow you to explore this unique resource in a flexible and enjoyable fashion.<br/><br/>We have decades of experience in helping customers build their own bespoke systems, boast the very finest international portfolio of any UK dealer, and offer a series of recently re-styled luxurious listening facilities ready to help you achieve a standard of musical reproduction that will easily surpass your expectations. <br/><br/>Owning a Music Room system is making an investment in your own happiness and well-being; it will serve as a daily reminder of just how rewarding your favourite recordings - perfectly reproduced - can be. <br /><br />We hope to see you <a href="mailto:musicroomglasgow@gmail.com?subject=Musical%20Bliss" ><strong>soon.</strong></a><br /><br />';
	$("#image_zero").attr("src", "images/components/systems/MR_red_m.jpg");
	$('#input').html(info);
	build_home_strip();
	update_selection('');

	}
				
		
							
					
			

function handle_tab_selections(){
	
	
		//if no types have been selected only look for brands
		if($('.tab[name="on"]').length == 0 && $('.btab[name="on"]').length > 1){
			loadthumbs_b();
				}
				
		//if no types have been selected only look for brands
		if($('.tab[name="on"]').length == 0 && $('.btab[name="on"]').length == 1){
		var brando = $('.btab[name="on"]').attr("id");
			brando = "#brand_" + brando;
			loadthumbs_b_only(brando);
				}
		
		//type only been checked
		
		if($('.btab[name="on"]').length == 0 && $('.tab[name="on"]').length > 0 ){
		//////alert('type only');
			loadthumbs_t();
				}

		//type and brand both selected
		if($('.btab[name="on"]').length > 0 && $('.tab[name="on"]').length > 0 ){
			loadthumbs_b_t();
				}	
				
				
		//if no types or brands, load home
		if($('.tab[name="on"]').length == 0 && $('.btab[name="on"]').length == 0){
		
		load_home();
	
				}


}

	

//---------------- THUMBNAILS FROM HERE -------------------//

//load thumbnails based on type alone
function loadthumbs_t(){
////////console.log("load_t");
auto_fox = 0; 
//update_selection('');
var current_types = [];
	var currently_on_t = $('.tab[name="on"]');
		for(var i=0; i<currently_on_t.length; i++){
			current_types.push(currently_on_t[i].id);
				}
				
		var all_thumbs =[];
		var all_types = [];
		var all_prods = [];
		var all_names = [];

		//get images with selected brand names in their src
			for(var j = 0; j<current_types.length; j++){
					var thumbs = $('#preload [name="' + current_types[j] + '"]');
							for(var x=0; x<thumbs.length; x++){
						all_thumbs.push(thumbs[x].src);
					all_types.push(thumbs[x].name);
				all_prods.push(thumbs[x].id);
			all_names.push(thumbs[x].alt);
			}
		}
build_strip(all_thumbs, all_types, all_prods, all_names);	
wanted_ids = all_prods;
}

//load based on brand and type?
function loadthumbs_b_t(){
////////console.log("load_b_t");
auto_fox = 0; 
//hash_s = '';
	var current_brands = [];
	var current_types = [];

//-------- set up the arrays ----------------//
	var currently_on_b = $('.btab[name="on"]');
		for(var i=0; i<currently_on_b.length; i++){
			current_brands.push(currently_on_b[i].id);
				}
							
	var currently_on_t = $('.tab[name="on"]');
		for(var i=0; i<currently_on_t.length; i++){
			current_types.push(currently_on_t[i].id);
				}
				
				var all_thumbs =[];
				var all_types = [];
				var all_prods = [];
				var all_names = [];
					
for(var j = 0; j<current_brands.length; j++){
	for(var s=0; s<current_types.length; s++){
	var thumbs = $('#preload img[src*="'+ current_brands[j] + '"][name="' + current_types[s] + '"]');
			for(var x=0; x<thumbs.length; x++){
			
						//add matched images to the all_ arrays
						all_thumbs.push(thumbs[x].src);
					all_types.push(thumbs[x].name);
				all_prods.push(thumbs[x].id);
			all_names.push(thumbs[x].alt);
			}
		}
	}
//var x = $("img[src$='twitter_logo_header.png'][name='logo']");			
build_strip(all_thumbs, all_types, all_prods, all_names);
wanted_ids = all_prods;						
}




function loadthumbs_b(){
////////console.log("load_b");
auto_fox = 0;
//hash_s = ''; 
	//get brands selected
	var current_brands = [];
	var currently_on_b = $('.btab[name="on"]');
		for(var i=0; i<currently_on_b.length; i++){
			current_brands.push(currently_on_b[i].id);
				}
				var all_thumbs = [];
					var all_types = [];
						var all_prods = [];
							var all_names = [];
							
					//get images with selected brand names in their src
					for(var j = 0; j<current_brands.length; j++){
						var thumbs = $('#preload img[src*="'+ current_brands[j] + '"]');
							for(var x=0; x<thumbs.length; x++){
						all_thumbs.push(thumbs[x].src);
					all_types.push(thumbs[x].name);
				all_prods.push(thumbs[x].id);
			all_names.push(thumbs[x].alt);
			}
		}
	//send info to build image strip including name/product_id	
build_strip(all_thumbs, all_types, all_prods, all_names);
wanted_ids = all_prods;
}



function loadthumbs_b_only(brando){
////////console.log("load_b_only");
	auto_fox = 0; 
	
	//update_hash('s', '');
	
	$('#content').css("margin-left", 0);
	$('.ext_shot').remove();
	$('.right_slider').fadeOut();
	$('.left_slider').fadeOut();

var sauce = $(brando).attr("src");
//////////console.log("IMAGE sauce: " + sauce);
$("#image_zero").attr("src", sauce);

	//get brands selected
	var current_brands = [];
	var currently_on_b = $('.btab[name="on"]');
		for(var i=0; i<currently_on_b.length; i++){
			current_brands.push(currently_on_b[i].id);
				}
				var all_thumbs = [];
					var all_types = [];
						var all_prods = [];
							var all_names = [];
							
					//get images with selected brand names in their src
					for(var j = 0; j<current_brands.length; j++){
						var thumbs = $('#preload img[src*="'+ current_brands[j] + '"]');
							for(var x=0; x<thumbs.length; x++){
						all_thumbs.push(thumbs[x].src);
					all_types.push(thumbs[x].name);
				all_prods.push(thumbs[x].id);
			all_names.push(thumbs[x].alt);
			}
		}
	//send info to build image strip including name/product_id	
build_strip(all_thumbs, all_types, all_prods, all_names);
wanted_ids = all_prods;
}



//FROM HERE CREATE ARRAY TO HOLD ALL INFO FOR ITEMS IN THE STRIP THEN JUST DOWNLOAD IMAGES WHEN REQUESTED
function build_strip(thumbs_A, types_A, prods_A, names_A){
	
	imagebar_width = 0;
		var image_string = '';
			for(var z=0; z<thumbs_A.length; z++){
				image_string += '<div class="im"><img class="thumbnail" src="' + thumbs_A[z] + '" id="'+ prods_A[z] +'" name="' + types_A[z] +'" /><div class="im_info_b" id="im_' + prods_A[z] +'">'+ names_A[z]  +'</div></div>';
			}
				$('#images').html(image_string);
					var x = $('#images .thumbnail');
						var y = 0;
							for(var g=0; g<x.length; g++){
								imagebar_width+=135;
									}
										$('#images').css("margin-left", 0);
											$('#images').css("width",imagebar_width);
											
											var bc = imagebar_width/820;
											var bc_up = Math.ceil(bc);
											add_dots(bc_up);
					
		//handle arrow
		if(imagebar_width > 860){
				$('#leftarrow').removeClass();
				$('#rightarrow').removeClass();
				$('#leftarrow').addClass("transparent_1");
				$('#rightarrow').addClass("transparent_1");
				}
			
		if(imagebar_width < 860){
				$('#leftarrow').removeClass();
				$('#rightarrow').removeClass();
				$('#leftarrow').addClass("transparent_0");
				$('#rightarrow').addClass("transparent_0");
				}
				
			}



	//maintain state in url
	function update_hash(){
	
		//////console.log("update_hash");
		hash_b = '$';
		hash_t = '@';
	
		var currently_types = $('.tab[name="on"]');
		var currently_brands = $('.btab[name="on"]');
	
		for(var ty=0; ty<currently_types.length; ty++){
			hash_t += '-' + currently_types[ty].id;
				}
		
		for(var br=0; br<currently_brands.length; br++){
			hash_b += '-' + currently_brands[br].id;
				}
		//////console.log("HS: " + hash_s);
		location.hash = hash_b + '/' + hash_t +'/' + hash_s;
	
		handle_tab_selections();
		
		manage_stack();
		
		
		
		//if thumb has been selected, put it up
		if(hash_s != ''){
		//////console.log("HS: " + hash_s);
		do_thumb_click(hash_s.substring(1));
			}
		
		var ur = "http://www.unbornbuddhamind.com/music-room/#";
		var email_me = document.getElementById('EM');
			email_me.innerHTML= '<a href="mailto:?subject=Musical%20Bliss&body=' + ur + hash_b + '/' + hash_t +'/' + hash_s + '"><img src="images/mbg.png" /></a>';
		
	
		};
		
		
		
		
function find_product_in_current(find_this){
	for(var a=0; a<current_products.length; a++){
		if(current_products[a].id == find_this){
			return a;
				}
			}return -1;
		}



	//get hash change
	$(window).hashchange( function() {
	var x = check_hash();
	//////console.log("changed_hash: " + x);
	if(x == 1){
	update_from_hash();
		}
		
	});
	
	
	
//make sense of changed hash - call updates on buttons if need be.
function check_hash(){
////////console.log("check_hash");
	var loc = String(window.location);
	var not_hashed = loc.indexOf("#");
	
	if(not_hashed == -1){
		return -1; //no hash
		}else{
		////////console.log("hashed" + loc);
		var h = (location.hash).substring(1);
		var h_split = [];
			h_split = h.split('/');
		var z = hash_b + '/' + hash_t +'/' + hash_s;
	
		//////console.log("internal: " + z + " Window: " + h);
	
	//new hash differs from what we thought it was 
	//need to check values before we just split it into the hash olders
	if(h != z ){
		var sensible = make_sense_of_new_hash(h_split);
		
		if(sensible == 1){
 			return 1; //hash has changed and we made sense of it
 				}else {return -1;} //changed but no sense could be made
		
		}else{
			return 0;//no change -> h==z so we have probably already done the update from the buttons
		}
	}

}

function make_sense_of_new_hash(h){
return 1;

}





//change the buttons pressed then 
function update_from_hash(){
//////console.log("FROM HASH");
hashing = 1;

	var h = (location.hash).substring(1);
		var h_split = [];
			h_split = h.split('/');
	

	//get arrays of selections
	var b_array = h_split[0].split('-');//brand
	var t_array = h_split[1].split('-');//type
	hash_s = h_split[2];//product
	////////console.log("HS: " + hash_s);
	hash_b = h_split[0];//set internals
	hash_t = h_split[1];//set internals
	
	//turn all buttons off
	$('.btab').attr("name", "off");
	$('.btab').removeAttr("style");
	$('.tab').attr("name", "off");
	$('.tab').removeAttr("style");
	
	//reset buttons according to new hash
	for(var a=1; a<b_array.length; a++){
	var ida = '#' + b_array[a];
	set_button_as_on_forsure(ida);
	}

	for(var b=1; b<t_array.length; b++){
	var ida = '#' + t_array[b];
	set_button_as_on_forsure(ida);
			}
			
	location.hash = hash_b + '/' + hash_t +'/' + hash_s;

	update_hash();
}









//get brands, get types, pass both to get images, pass json result to layout function
//---------------- GET RESULTS FROM DB BASED ON TAG FILTERS -----------------------------------//
function manage_stack(){
		//////console.log("manage stack: " );
		var currently_on = $('.tab[name="on"]');
		var currently_on_b = $('.btab[name="on"]');

		var current_types = [];
		var current_brands = [];

		var brands_on=0;
		var types_on=0;

		//find the brands and types added to the search
		for(var i=0; i<currently_on.length; i++){
			current_types.push(currently_on[i].id);
				types_on++;
					}

		for(var i=0; i<currently_on_b.length; i++){
			current_brands.push(currently_on_b[i].id);
				brands_on++;
					}

		//nothing selected then blank the product array and NEEDS TO>>>>>remove details
		if(brands_on == 0 && types_on ==0){
			//current_products = [];	
				}else{
				//////console.log("BRAND: " + current_brands[0]);
			
				var server_request = check_for_ids(current_types, current_brands);
				
					if(server_request == 1){
					$.post("get_images.php", {
					b_o: brands_on,
					t_o: types_on,
					'brands[]': current_brands,
					'types[]': current_types
						}, function(data){
							if(data != 0){
								var xyz = JSON.parse(data);
								if(types_on == 0){
								////console.log("doing brand");
								merge_brand(xyz);	
								do_layout(current_types, current_brands);
								}else{
								////console.log("doing desc only");
								merge_descriptions(xyz.descriptions);	
								do_layout(current_types, current_brands);
										}
									}
								});
							}else{
							do_layout(current_types, current_brands);
							}
								
								
								
						//do_layout(current_types, current_brands);		
							}
					//handle info panel for those too slow to do it themselves	
					if(brands_on == 1 && types_on ==0){	
					var x=document.getElementById("tabbed_input");
    					if(x){
    						load_with_delay();
    								}
								}
							}
							
							
							
							

function check_for_ids(current_types, current_brands){
	
	if(current_types.length == 0 && current_brands == 1){
	var brand_request = do_we_have_this_brand(current_brands[0]);
		if(brand_request < 0)
		{
		return 1;//request needed
			}
		}
	
for(var a=0; a< wanted_ids.length; a++){
	var gt = got_this(wanted_ids[a]);
		if(gt < 0){
			return 1;//request needed
			}
		}

	return -1;//NO REQUEST needed

}


function do_we_have_this_brand(shortie){

	for(var x=0; x<current_brand_details; x++){
		if(current_brand_details[x].short == shortie){
			return 1;//got it
			}
		}return -1;//don't got it
	}
				
				
//is this id in the current set of descriptions?	
function got_this(id){

	for(var x=0; x<current_products.length; x++){
		if(current_products[x].id == id){
			return 1;
				}
			}return -1;//not found
		}			
					
					

function merge_descriptions(desc){
////console.log("merge desc");
var clean_desc = remove_duplicates(desc);

for(var i=0; i<clean_desc.length; i++){
current_products.push(clean_desc[i]);
//////console.log("DESC: " + desc[i].id);
}

//////console.log("cpl: " + current_products.length);

//////console.log("desc len: " + clean_desc.length);

merge_sort(current_products, 0, current_products.length - 1);

//////console.log("LEN: " + current_products.length);
for(var z=0; z<current_products.length; z++){
//////console.log("ID: " + current_products[z].id);
}

}		
							
		
function remove_duplicates(d){

var temp = [];

for(var x=0; x<d.length; x++){
	var g = got_this(d[x].id);
	if(g<0){
	temp.push(d[x]);
		}
	}
	return temp;
}
					
							
function  merge_sort(array_one, left, right){
	//////console.log("MS");
	var array_two = new Array();
	do_merge_sort(array_one, left, right, array_two);
		
		}




function do_merge_sort(array_one, left, right, array_two){
//////console.log("DMS");
	if(left<right){
	var m = parseInt((left+right)/2);
	//////console.log("M: " + m);
	do_merge_sort(array_one, left, m, array_two);
	do_merge_sort(array_one, m+1, right, array_two);
	merge(array_one, left, m, array_one, m+1, right, array_two, 0);
	
	for(var k=left; k<=right; k++){
	array_one[k] = array_two[k-left];
		
		}
	}
}



//merge without duplicates...
function merge(array_one, left1, right1, array_two, left2, right2, array_three, left3){
//////console.log("M");
		var i = left1; 
		var j = left2;
		var k = left3;

	while(i<=right1 && j <=right2){
		var comp = compare_values(array_one[i], array_two[j]);
	
	if(comp < 0){
	array_three[k++] = array_one[i++];
	}else if(comp > 0){
	array_three[k++] = array_two[j++];
	}else{
	array_three[k++] = array_one[i++];
	j++;
	}
	while(i<=right1){
	array_three[k++] = array_one[i++];
	}
	while(j<=right2){
	array_three[k++] = array_two[j++];
			
			}
		}
	}



function compare_values(a,b){
	//////console.log("A: " + a.id + " B: " + b.id);
	return (a.id - b.id);

	}


function get_brand(b){

for(var a=0; a<current_brand_details.length; a++){
if(current_brand_details[a].short == b){
return current_brand_details[a];
}
}return -1;

}

					
				
//--------- END THUMBNAILS AND GENERAL HOUSEKEEPING -------------//



function layout_brand(b){
		////console.log("BRA: " + b[0]);
		var json_input = get_brand(b[0]);
		//////console.log(json_input);
		if(json_input != -1){
		
		var b_name = json_input.name;
		var url = json_input.url;
		var text = json_input.text;
		var str = '';
		var arrow = '<div class="lnk" ><img src="images/small_round.gif" /></div>';
		
			//if we have a product review do the layout for that ====----//	
			if(json_input.quote.length>0){
				str+= '<div class="rev">';
				str+= '<div class="intro">' + json_input.qintro +'</div>';
					if(json_input.qlink.length>8){	
				str += '<a href="' + json_input.qlink +'" target="_blank">';}
				str += '<div class="big_quote left"><div class="inner_quote">\u201c</div></div><div class="quote">'; 
				str += json_input.quote + '<div class="BQ">\u201d</div></div><div class="attr">';
								
			if(json_input.qlink.length>8){
				str += arrow;}

				str +='<div class="attr_w">';
				str += json_input.qattr + '</div></div>';
										
			if(json_input.qlink.length>8){
				str += '</a>';}
				str += '</div>';}
												
												
				
				if(hash_s==''){
			var info = '<div class="close"></div><div class="info_wrapper"><div class="headsup"><span class="component">';
				info += b_name +'</span><br /><br />';
				info +=  text + '<br/><br/></div>'+ str +'</div><div class="more"> <a href="' + url + '" target="_blank"> manufacturer</a></div>';
				
			var burl = 'images/components/'+ json_input.short  +'/' + json_input.image;
				$("#image_zero").attr("src", burl);
				//console.log("info: " + info);
				$('#input').html(info);
				current_content = info;
						}
						
				}else{load_home();}
				
				//stick the info for current image box products into a global.
				//current_products = json_input.descriptions;
					
					//merge_descriptions(json_input.descriptions, "brand");
					}//ENDS



function layout_both(b, t){
////console.log("layout both");
	var json_input = get_both(b,t);



	$('#content').css("margin-left", 0);
	$('.ext_shot').remove();
	$('.right_slider').fadeOut();
	$('.left_slider').fadeOut();
			if(hashing == 0){
				first_thumb("both");
						}
					
				}//ENDS
	

			
function get_both(b,t){};
			

//----------------HANDLE LAYOUT CONDITIONAL ON JSON INPUT TYPE -> BRAND | -----------------------------------//
function do_layout(ct, cb){
////console.log("do_layout");
	
	////BRAND ONLY-------//
	if(cb.length>0 && ct.length==0){
		if(hashing==0){
			update_selection('');
			}
			layout_brand(cb);
			
			}
	
	//BRAND AND TYPE-----------//
	if(ct.length>0){
		//merge_descriptions(json_input.descriptions);
		
			layout_both(cb, ct);		
					}
				
	//do_type_collation();					
				}
								
					
function merge_brand(b){
////console.log("merge brand " + b.brand_details.short );

	var g = do_we_have_this_brand(b.brand_details.short);
		if(g<0){
			current_brand_details.push(b.brand_details);
			merge_descriptions(b.descriptions);
					}
				}






////------------------------HELPERS-------------------------------//




function get_one_product(num){
	var one_prod = [];
		for(var i=0; i<current_products.length; i++){
			if(current_products[i].id == num){
				one_prod.push(current_products[i].name);
					one_prod.push(current_products[i].brand);
				return one_prod;
			}else{
		return [0,0];
			}
		}
	}
					

function add_room_deets(){
	var incoming = $('.roomnail');
		
		for(var a=0; a<incoming.length; a++){
			var deets = incoming[a].name;
			var newid =  incoming[a].id;
			var showroom = document.getElementById(newid);
			var showroom_info = showroom.parentNode;
			var new_element = document.createElement('div');
		
					new_element.className='im_info_b';
				new_element.innerHTML = deets;
			showroom_info.appendChild(new_element);
					}
				}//end deets				
				
				
		function build_home_strip(){
var im_arr = $(".home");
		imagebar_width = 0;
	var image_string = '';
			
			for(var z=0; z<im_arr.length; z++){
				image_string += '<div class="im"><img class="roomnail" src="' + im_arr[z].src + '" name="' + im_arr[z].alt +'" id="N_' + im_arr[z].id + '" /></div>';
										}
				$('#images').html(image_string);
					var x = $('#images .roomnail');
						var y = 0;
							for(var g=0; g<x.length; g++){
								imagebar_width+=135;
									}
										$('#images').css("margin-left", 0);
											$('#images').css("width",imagebar_width);
											var bc = imagebar_width/820;
											var bc_up = Math.ceil(bc);
											add_dots(bc_up);
											add_room_deets();
					
		//handle arrow
		if(imagebar_width > 860){
				$('#leftarrow').removeClass();
				$('#rightarrow').removeClass();
				$('#leftarrow').addClass("transparent_1");
				$('#rightarrow').addClass("transparent_1");
				}
			
		if(imagebar_width < 860){
				$('#leftarrow').removeClass();
				$('#rightarrow').removeClass();
				$('#leftarrow').addClass("transparent_0");
				$('#rightarrow').addClass("transparent_0");
				}
				
			}





$('.roomnail').live('mouseup', function() {
				
	var a = this.src;
		a = a.substr(0, (a.length)-6) + '.jpg';
	var pid = this.id;
	var t = "#" + pid;
	var u = 'url("' + a + '")';
	var t = "#" + pid;
	var deets_box_id = "#im_" + pid;
						
	//reset deets bg and text
	$('.im').css("background-color", 'rgb(237,238,239)');
	$('.im_info_b').css("font-weight", '100');
	$('.im_info_b').css("color", 'rgb(53,53,53)');
					
	//highlight in-play
	$(t).parent().css("background-color", 'rgb(53,53,53)');
	$(t).next().css("color", 'rgb(250,251,252)');
	$(deets_box_id).css("font-weight", '500');
					
	var bgImg = new Image();
		bgImg.src = a;
		bgImg.onload = function(){
   			$("#image_zero").fadeOut('slow', function() {
        	$("#image_zero").attr("src", a).fadeIn('slow', function() {

	//var wrap = document.getElementById('headsup');
	//wrap.innerHTML = '<p class="systemz">' + n + '</p>';
	
        				});
					});
				};
			});
					








function animate_info_out(){
$("#input").animate({
   marginLeft: "-420px"
  }, 1000, 'easeOutCirc', function() {
    // Animation complete. Add info tab
  	var info_tab = document.createElement('div');
  		info_tab.id = "tabbed_input";
			info_tab.className='tabbed';
			
			$("#content_holder").prepend(info_tab);
				//var content_window = document.getElementById("content_holder")
					//content_window.appendChild(info_tab);
  						});
					}





function animate_info_in(){
		$("#tabbed_input").remove();
			$("#input").animate({
   				marginLeft: "0px"
  					}, 1000, 'easeOutBounce');
						}

function load_with_delay(){
var t_o = setTimeout(animate_info_in, 3000);
}


function opening_gambit(){
////////console.log("awright boysie?");
if(window.location != 'http://www.unbornbuddhamind.com/music-room/' && linked_in===0){

update_from_hash();
}
var t_o = setTimeout(animate_info_in, 3000);
}



});



