var scroll_position = 0;
var allData;
var scrollDistance = 53;
var scrollRight = false;
var scrollLeft = false;
var timingoutToHide = false;
var pid = 0;
var uid = 0;
var inquriyBubbleHidden = false;
var timingOutToHideTagBubbles = false;
var bubbleIdShowing = "";

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

function urlParam(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null){return "";}
  else{return results[1];}
}

function ShowResults(a) {
    //document.body.scrollTop = 0;
    //window.scroll(0,0);
    $('#footer-image').css('visibility','hidden');
    HideBubbles();
    is_string = false;
    if (typeof a.match != 'undefined') 
    	is_string = true;
    if (!a && !is_string)
    	return false;
    $.getJSON((!is_string)?a.href:a, function(json){
        var html = "";
        allData = json;
        /* Build the HTML string that will be injected into the scroller */
        for (var x=0;x<json.length;x++){
            if (json[x].images != null && json[x].images.small!=null)
                html+='<div class="img" onclick="ShowProduct('+x+');" style="vertical-align:center;"><img style="max-height:75px;max-width:50px;" src="http://static.uvalux.com/'+json[x].images.small.picture+'" alt="'+json[x].name+'" /></div>';            
        }
        /* Show & hide the left and right arrows depending on how many results are in the viewer */
        if (json.length<=9) { 
            $('div#scroll-right').hide();
            $('div#scroll-left').hide();
        } else {
            $('div#scroll-right').show();
            $('div#scroll-left').show();
        }
        scroll_position=0;
        $('div#scrollable').html(html).css('margin-left',"0px"); //reset the image offset
        $('div#scroll-left').hide(); //hide the left arrow, not needed when first loading
        $('div#blackout').show(); //show the overlay
        $('div#results').show(); //show the proudct details
		$('html').css({'overflow':'hidden'});
        ShowProduct(0); //load up first product in the category
    });
    return false;
}

function ShowProduct(p) {
	var tags = '';
	var inquiry = '';
    var product = allData[p];
    $('div#product-details div#product-title').html(product.name);
    $('div#product-details div#product-image').html('<div id="loading" style="visibility:hidden;position:absolute;float:right;margin-left:230px;margin-top:15px;"><img src="http://static.uvalux.com/i/spinner.gif" /></div><div style="text-align:center;"><img src="http://static.uvalux.com/'+product.images.large.picture+'" alt="'+product.name+'" style="max-height:400px;max-width:267px;"/></div>');
    
    $('div#product-details div#product-description').html(product.description); 
	for(tag in product.categories) {
		tag_desc = product.categories[tag][3];
		tags += '<div class="browser-tag-images" id="id_'+ product.categories[tag][1] + '" style="float:left;margin-top:0px;width:60px;height:60px;margin-bottom:5px;margin-left:5px;"><a href="/products/' + product.category +'/' + product.categories[tag][1] + '/" class="product-tag-image"><img src="http://static.uvalux.com/' + product.categories[tag][2] + '" height="60" width="60" /></a>';
        if (tag_desc.length != 7) {
            tags += '<div class="tag-image-bubble" id="bubble1_id_' + product.categories[tag][1] + '" style="color:#black;font-size:11px;padding-top:10px;margin-top:-217px;margin-left:-30px;position:relative;">' + tag_desc + '</div>';
        }
        tags += '</div>';
    }
    
    
    if (product.me && !product.employee){
        uid = product.me;pid = product.id;
        tags += '<div class="inquiry" id="id_inquire" style="float:left;margin-top:0px;width:60px;height:60px;margin-bottom:5px;margin-left:5px;"><a href="/products/' + product.category +'/' + product.categories[tag][1] + '/" class="product-tag-image"><img src="http://static.uvalux.com/i/inquiry-left-torn.png" height="60" width="60" /></a>';
        tags += '<div class="tag-image-bubble1" id="bubble1_id_inquiry" style="color:#black;font-size:11px;padding-top:10px;margin-top:-217px;margin-left:-30px;position:relative;">This button will help notify your sales representative that you have an inquiry regarding this product.</div>';
        tags += '</div>';
    }
    
	$('div#product-details div#product-tags').html(tags);
	
	$('.browser-tag-images').each(function() {
	   var distance = 10;
	   var time = 250;
	   var hideDelay = 500;
	   var hideDelayTimer = null;
	   var showDelayTimer = null;
	   var beingShown = false;
	   var shown = false; 
	   var trigger = $('.product-tag-image', this);
	   var popup = $('.tag-image-bubble', this);
	   trigger.click(function(){$('#loading').css({'visibility':'visible'});ShowResults(this);return false;})
	   popup.click(function(){ShowResults(trigger.get(0).href);return false;})
	   $([trigger.get(0), popup.get(0)]).mouseover(function() {
	       if (showDelayTimer)clearTimeout(showDelayTimer);
	       if (hideDelayTimer)clearTimeout(hideDelayTimer);
	       if (beingShown || shown){return false;}
	       else{beingShown = true;showDelayTimer = setTimeout(function() { popup.css({top:0+'px',display:'block'}).animate({top:'-='+distance+'px',opacity:1},time,'swing',function(){beingShown=false;shown=true;});}, 1000); }
	   }).mouseout(function() { 
	       if (showDelayTimer)clearTimeout(showDelayTimer);
	       if (hideDelayTimer) clearTimeout(hideDelayTimer);
	       hideDelayTimer=setTimeout(function(){hideDelayTimer=null;shown=false;
	           popup.animate({top:'-='+distance+'px',opacity:0},time,'swing',function(){shown=false;beingShown=false;popup.css({'top':'-30px','display':'none'});});},hideDelay);
	   });
	});
	
	$('#id_inquire').each(function() {
        var distance = 10;
        var time = 250;
        var hideDelay = 500;
        var hideDelayTimer = null;
        var showDelayTimer = null;
        var beingShown = false;
        var shown = false; 
        var popup = $('.tag-image-bubble1');
        var trigger = $('.inquiry');
        trigger.click(function(){if(uid != 0){AddToInquiry(pid,uid);}return false;});
        popup.click(function(){if(uid != 0){AddToInquiry(pid,uid);}return false;});
        $([trigger.get(0), popup.get(0)]).mouseover(function() {
           if (showDelayTimer)clearTimeout(showDelayTimer); 
	       if (hideDelayTimer)clearTimeout(hideDelayTimer);
	       if (beingShown || shown){return false;}
	       else{beingShown = true;showDelayTimer = setTimeout(function() { popup.css({top:0+'px',display:'block'}).animate({top:'-='+distance+'px',opacity:1},time,'swing',function(){beingShown=false;shown=true;});}, 1000);}
	   }).mouseout(function() {
	       if (showDelayTimer)clearTimeout(showDelayTimer); 
	       if (hideDelayTimer) clearTimeout(hideDelayTimer);
	       hideDelayTimer=setTimeout(function(){hideDelayTimer=null;shown=false;
	           popup.animate({top:'-='+distance+'px',opacity:0},time,'swing',function(){shown=false;beingShown=false;popup.css({'top':'-30px','display':'none'});});},hideDelay);
	   });
	});
}

function AddToInquiry(pid,uid){
	$('#loading').css({'visibility':'visible'});
	$.post('/products/inquire/',{'pid':pid,'uid':uid},function(data){
		$('#loading').css({'visibility':'hidden'}); 
		if(data[0].status){$.jGrowl("Failed to add product to inquiry",{life:1500});return false;}	
		id = data[0].id;
		el = $('#confirm-link');
		if (el.attr('href')){el.attr('href','/confirm-inquiry/'+id+'/');}
		else{$('#login-links').append('<a href="/confirm-inquiry/'+id+'/" id="confirm-link" class="confirm-link" onClick="ConfirmInquiry(this);return false;">Confirm Inquiry</a>');}
		$.jGrowl("Product added to inquiry",{life:1500});	
	},"json"); 
}

function Scroll(dir) {
   var maxLength = (allData.length * scrollDistance) * -1;
    if (dir == "left") {
        if (scroll_position < 0) {
            scroll_position+=scrollDistance;
            $('div#scrollable').fadeOut(100, function(data) { 
                $('div#scrollable').css("margin-left", scroll_position +"px");
                $('div#scrollable').fadeIn(100);
            });
            if (scroll_position == 0) { 
                $('div#scroll-left').hide();
                scrollLeft = false;
            } else
                $('div#scroll-right').show();
        }
    } else if (dir == "right") {
        scroll_position-=scrollDistance;
        $('div#scroll-left').show();
        $('div#scrollable').fadeOut(100, function(data) {
            $('div#scrollable').css("margin-left", scroll_position + "px");
            $('div#scrollable').fadeIn(100);
        });
        if (scroll_position > (maxLength + (9 * scrollDistance)))
            $('div#scroll-right').show();
        else {
            $('div#scroll-right').hide();
            scrollRight = false;
        }
    }
}

$(document).ready(function () {
    if(urlParam('tag')){url=location.pathname.toString();url+=(urlParam('tag')?urlParam('tag'):'')+'/';url+=(urlParam('tag2')?urlParam('tag2'):'')+'/';ShowResults(url);}
    
    //$('div.tag-images a').mouseover(function(){ShowBubble('bubble_'+this.id);}).click(function(){ShowResults(this);return false;}).mouseout(function(){HideBubbles();}); 
    $('.product-tag-image').click(function(){ShowResults(this); return false;});
    /*$('div.tag-image-bubble').mouseover(function(){HideBubbles();ShowBubble('bubble_'+this.id);}).click(function(){ShowResults($(this).parent().find('a:first-child')[0]);return false;}).mouseout(function(){HideBubbles();})*/;
    //$('div.product-tag').mouseover(function(){ShowBubble('bubble_'+this.id);}).mouseout(function(){HideBubbles();});
    //$('.inquiry-torn').mouseover(function(){ShowBubble('inquiry-bubble');/*setTimeout("StartFadeOut('.inquiry-bubble');", 4750);*/ return false;}).mouseout(function(){HideBubbles();}).click(function(){if(uid != 0){AddToInquiry(pid,uid);}});
    
    
    $('div.close-torn').click(function(){HideResults();$('#footer-image').css('visibility','visible');return false;});
    $('div#scroll-left').click(function(){Scroll("left");});
    $('div#scroll-right').click(function(){Scroll("right");});
	$('div.team-member-bubble').mouseout(function(){timingoutToHide=true;setTimeout("TimedOutBubbleHide();",1000);});
	$('div.team-member-bubble').mouseover(function(){timingoutToHide=false;});
	$('.team-member').click(function(){
		var span = $(this).parent().parent().parent().find('span:first-child')[0];
		var ua = window.navigator.userAgent
      	var msie = ua.indexOf("MSIE ")
		if (msie > 0) {
			$('div#team-member-bubble-'+this.id).css({'top':span.parentNode.offsetTop+317});
			$('div#team-member-bubble-'+this.id).css({'left':span.parentNode.offsetLeft+179});
		} else {
			$('div#team-member-bubble-'+this.id).css({'top':span.offsetTop+95});
			$('div#team-member-bubble-'+this.id).css({'left':span.offsetLeft});
		}
		HideBubbles(); 
		ShowBubble('team-member-bubble-' + this.id); return false;
		timingoutToHide = true;
		setTimeout("TimedOutBubbleHide();", 2000); 
	});
	$('.submit-team-question').click(function() {
		var name = $('#name-'+this.id).val();
		var email = $('#email-'+this.id).val();
		var question = $('#question-'+this.id).val();
		$.post('/about/our-team/question/',{'n':name,'e':email,'q':question,'i':this.id},function(data){if(data=='successful'){$.jGrowl("Your question has been sent!",{life:2500});}});
		$('#name-'+this.id).val('');
		$('#email-'+this.id).val('');
		$('#question-'+this.id).val('');
		HideBubbles(); 
	});
	$('.confirm-link').click(function(){ });
	$('.scroll-right').mouseover(function(){scrollRight=true;setTimeout("ScrollProductsRight();",1250);});
	$('.scroll-right').mouseout(function(){scrollRight=false;});
	$('.scroll-left').mouseover(function(){scrollLeft=true;setTimeout("ScrollProductsLeft();",1250);});
	$('.scroll-left').mouseout(function(){scrollLeft=false;});
	
	/*$('.inquiry-torn').each(function() {
        var distance = 10;
        var time = 250;
        var hideDelay = 500;
        var hideDelayTimer = null;
        var beingShown = false;
        var shown = false; 
        var popup = $('.inquiry-bubble');
        var trigger = $('.inquiry-torn');
        trigger.click(function(){if(uid != 0){AddToInquiry(pid,uid);}});
        $([trigger.get(0), popup.get(0)]).mouseover(function() {
	       if (hideDelayTimer)clearTimeout(hideDelayTimer);
	       if (beingShown || shown){return false;}
	       else{beingShown = true;popup.css({top:0+'px',display:'block'}).animate({top:'-='+distance+'px',opacity:1},time,'swing',function(){beingShown=false;shown=true;});}
	   }).mouseout(function() { 
	       if (hideDelayTimer) clearTimeout(hideDelayTimer);
	       hideDelayTimer=setTimeout(function(){hideDelayTimer=null;shown=false;
	           popup.animate({top:'-='+distance+'px',opacity:0},time,'swing',function(){shown=false;beingShown=false;popup.css({'top':'-30px','display':'none'});});},hideDelay);
	   });
	});*/
	
	$('.product-link-image').click(function() {
		ShowResults(this);
		return false;
	});

	$('.tag-image, .product-tag').each(function() {
	   var distance = 10;
	   var time = 250;
	   var hideDelay = 500;
	   var hideDelayTimer = null;
	   var showDelayTimer = null;
	   var beingShown = false;
	   var shown = false; 
	   var trigger = $('.tag-image-link', this);
	   var popup = $('.tag-image-bubble', this);
	   trigger.click(function(){ShowResults(this);return false;})
	   popup.click(function(){ShowResults(trigger.get(0).href);return false;})
	   $([trigger.get(0), popup.get(0)]).mouseover(function() {
	       if (showDelayTimer)clearTimeout(showDelayTimer);
	       if (hideDelayTimer)clearTimeout(hideDelayTimer);
	       if (beingShown || shown){return false;}
	       else{beingShown = true;showDelayTimer = setTimeout(function() { popup.css({top:0+'px',display:'block'}).animate({top:'-='+distance+'px',opacity:1},time,'swing',function(){beingShown=false;shown=true;}); }, 1000); }
	   }).mouseout(function() { 
	       if (showDelayTimer) clearTimeout(showDelayTimer);
	       if (hideDelayTimer) clearTimeout(hideDelayTimer);
	       hideDelayTimer=setTimeout(function(){hideDelayTimer=null;shown=false;
	           popup.animate({top:'-='+distance+'px',opacity:0},time,'swing',function(){shown=false;beingShown=false;popup.css({'top':'-30px','display':'none'});});},hideDelay);
	   });
	});
	
	$('.tag-images1').mouseover(function() { document.title='test'; })
});

function HideResults(){$('html').css({'overflow':'auto'});$('div#blackout').hide();return false;}
var previousBubble = "";
var bubbleTimeout = null;
function ShowBubble(id){
    if (bubbleTimeout) { clearTimeout(bubbleTimeout); }
    $('div#'+id).fadeIn("slow");
    previousBubble = id;
}
function HideBubbles(){
    if (bubbleTimeout) { clearTimeout(bubbleTimeout); }
    bubbleTimeout = setTimeout(function() { 
        bubbleTimeout = null;
        $('div.tag-image-bubble').fadeOut("fast");
        $('div.team-member-bubble').fadeOut("fast");
        $('.inquiry-bubble').fadeOut("fast");
 
    }, 500);
}
function ConfirmInquiry(a){$.post(a.href,function(data){if(data=='successful'){$('.confirm-link').remove();$.jGrowl("Inquiry has been confirmed.",{life:1500});}});}
function TimedOutBubbleHide(){if(timingoutToHide)HideBubbles();}
function StartFadeOut(el){$(el).fadeOut("slow");bubbleIdShowing = "";}
function ScrollProductsRight(){if(scrollRight){Scroll("right");setTimeout("ScrollProductsRight();",500);}}
function ScrollProductsLeft(){if(scrollLeft){Scroll("left");setTimeout("ScrollProductsLeft();",500);}}
