//function vIE(){return (navigator.appName=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;}
//var ieVer = vIE();
var plugins = null;


    function Timer(){
    this.obj = (arguments.length)?arguments[0]:window;
    return this;
    }

    // The set functions should be called with:
    // - The name of the object method (as a string) (required)
    // - The millisecond delay (required)
    // - Any number of extra arguments, which will all be
    // passed to the method when it is evaluated.

    Timer.prototype.setInterval = function(func, msec){
    var i = Timer.getNew();
    var t = Timer.buildCall(this.obj, i, arguments);
    Timer.set[i].timer = window.setInterval(t,msec);
    return i;
    }
    Timer.prototype.setTimeout = function(func, msec){
    var i = Timer.getNew();
    Timer.buildCall(this.obj, i, arguments);
    Timer.set[i].timer = window.setTimeout("Timer.callOnce("+i+");",msec);
    return i;
    }

    // The clear functions should be called with
    // the return value from the equivalent set function.

    Timer.prototype.clearInterval = function(i){
    if(!Timer.set[i]) return;
    window.clearInterval(Timer.set[i].timer);
    Timer.set[i] = null;
    }
    Timer.prototype.clearTimeout = function(i){
    if(!Timer.set[i]) return;
    window.clearTimeout(Timer.set[i].timer);
    Timer.set[i] = null;
    }

    // Private data

    Timer.set = new Array();
    Timer.buildCall = function(obj, i, args){
    var t = "";
    Timer.set[i] = new Array();
    if(obj != window){
    Timer.set[i].obj = obj;
    t = "Timer.set["+i+"].obj.";
    }
    t += args[0]+"(";
    if(args.length > 2){
    Timer.set[i][0] = args[2];
    t += "Timer.set["+i+"][0]";
    for(var j=1; (j+2)<args.length; j++){
    Timer.set[i][j] = args[j+2];
    t += ", Timer.set["+i+"]["+j+"]";
    }}
    t += ");";
    Timer.set[i].call = t;
    return t;
    }
    Timer.callOnce = function(i){
    if(!Timer.set[i]) return;
    eval(Timer.set[i].call);
    Timer.set[i] = null;
    }
    Timer.getNew = function(){
    var i = 0;
    while(Timer.set[i]) i++;
    return i;
    }






function bj_coffeefinder(options)
{
	this.loading = "";
	this.timer = new Timer(this);
	this.timeKeeper = null;
	this.loadCount = 0;
	this.totalToLoad = 2;
	this.data = {};
    this.level ='';
    this.host = (("https:" == document.location.protocol) ? "https://" : "http://");
    this.server = this.host+'www.bocajava.com';
	if(options.path==null) this.path = this.server+'/bocajava/plugins/coffeefinder/';
	else this.path = options.path;
	if(options.inline == null) this.inline = false;
    if(options.key!=null)
        {
            this.lfeClass = 'guest_bg';
            this.key = options.key;
        }
    else this.key = null;
    this.linked = true;
    if(options.linked!=null) this.linked = options.linked;

	this.containerHTML = '<div id="bj_modal" class="'+this.lfeClass+'"><div id="bj_loading"><img src="'+this.path+'images/cuploading.gif" /></div><div id="bj_head"></div><div id="bj_menuarrow"></div><div id="bj_menu"><ul><li><a href="#Flavor" id="bj_menu_flavor"></a></li><li><a href="#Light" id="bj_menu_light"></a></li><li><a href="#Medium" id="bj_menu_medium"></a></li><li><a href="#Dark" id="bj_menu_dark"></a></li></ul></div><div class="sliderGallery" id="bj_results"></div></div>';
	
	
	this.debug = function($msg) {
          if (window.console && window.console.log)
            window.console.log($msg);
          else alert($msg);
        };
	
	var obj = this;


	
	this.loadContent = function(file, id, type)  //dynamically append javascript files
	{
	  var head = document.getElementsByTagName('head').item(0)
	  var scriptTag = document.getElementById(id);
	  if(scriptTag) head.removeChild(scriptTag);
	  
	  if(type=="script")
	  {
	    script = document.createElement('script');
	    script.src = obj.path + file;
		script.type = 'text/javascript';
		script.id = id;
		head.appendChild(script);
		
	  	obj.loading = id;
		obj.timeKeeper = this.timer.setTimeout("checkLoaded", 1000);
	   }	
	   else
	   {
	   	 script = document.createElement('link');
	     script.href = obj.path + file;
		 script.rel = 'stylesheet';
		 script.id = id;
		 head.appendChild(script);
	   }
	}
	
	this.checkLoaded = function() //make sure the external files are all loaded in
	{
		obj.loadCount++;
		if(obj.loadCount == obj.totalToLoad) obj.run();
	}
	
	
	this.run = function()
	{
        obj.loadGraphics();
        jQuery.ifixpng(obj.path+'images/pixel.gif');
		if(obj.inline == false) // this is a modal window, so we'll open it on-click
		{
			jQuery(options.tag).click(function(){
				obj.openModal();
   				return false;	
			});
		}
      
	}
	
	this.openModal = function()
	{
	
		jQuery(obj.containerHTML).modal({onOpen: function (dialog) {
		jQuery("#bj_modal div").ifixpng();
		jQuery("a.modalCloseImg").ifixpng();
		  dialog.overlay.fadeIn('slow', function () {
			dialog.container.fadeIn('slow', function () {
			  dialog.data.fadeIn('slow'); 
			  obj.startDecision();
			});
		  });
		},
		
		onClose: function (dialog) {
		  dialog.data.fadeOut('slow', function () {
			dialog.container.fadeOut('slow', function () {
			  dialog.overlay.fadeOut('slow', function () {
				$.modal.close(); // must call this to have SimpleModal
								 // re-insert the data correctly and
								 // clean up the dialog elements
			  });
			});
		  });
		},
		opacity:80,
		containerId: 'bj_modalContainer'		
		});
	}
	
	
	this.setActiveClass = function(clicked)
	{
		jQuery("#bj_roast a").each(function(){
			if(jQuery(this).attr('class').match(/active/gi) !=null) jQuery(this).removeClass('active');
		});
		
		jQuery(clicked).addClass('active');
	}
	
	this.runClick = function(element)
	{
		var modalOffset = $("#bj_modal").offset();
		var offset = $(element).offset();
		var l = (offset.left - modalOffset.left);
		var c = l + ($(element).width()/2);
		
		var $arrow =$("#bj_menuarrow");
		var a_offset = $arrow.offset();
		var al = (a_offset.left - modalOffset.left);
		
		var moveTo = c - $arrow.width()/2;
		
		$arrow.animate({left:moveTo});
	}
	
	this.loader = function()
	{
		var $loader = $("#bj_loading");
		if($loader.is(':hidden'))
		{
			$loader.css({display:'block',opacity:0}).animate({opacity:.8},500);
		}
		else
		{
			$loader.animate({opacity:0},500,function(){$(this).css({display:'none'})});
		}
	}
	
	this.startDecision = function()
	{
	/*
		jQuery("#bj_menu a").mouseover(function(){
			obj.runHover(this);
		});
	*/
		jQuery("#bj_menu a").click(function(){
		
			obj.runClick(this);
			obj.loader();
		
			var url = jQuery(this).attr('href');
			
			url_a = url.split('#');
			url = url_a[1];	
            obj.level = url;
			obj.getResults();
		});


       obj.runOnce();
	}

    this.runOnce = function(){
        obj.loader();
        obj.level = 'Flavor';
        obj.runClick("#bj_menu_flavor");
        obj.getResults();
    }


    this.getResults = function(){
        var p = {};
        p['level'] = obj.level;
        if(obj.key!=null) p['userKey'] = obj.key;
        if(obj.data[obj.level] == null)
        {
        //jsonp request goes here to get back data
        jQuery.ajax({
						   url: obj.server+'/viewProductsByRoastIndicator.do',
						   data:p,
						   dataType: 'jsonp',
						   success: function(data){
                             obj.data[obj.level] = data;
                             obj.renderDecision();
                           },
						   error:obj.responseError
						 });

        } else {obj.renderDecision();}
    }

	
	this.renderDecision = function()
	{
	
		var baseHTML = '<ul class="items"></ul>';
		var listHTML = '';
		var sliderHTML = '';
		var count = 0;
		
		
		jQuery.each(obj.data[obj.level].items, function(i,item){
			count++;

            var pNameA = item.productName.split('-');
            var pName = pNameA[0];

            if(pName.match(/lee/gi)) pName = 'Caramel Kiss Island';
            if(pName.match(/frosty/gi)) pName = 'Frostys Favorite';
			pName = pName.replace(/coffee/gi,'');

			var img =pName.replace(/\s/gi,'');
          
			img+='.png';

            if(!pName.match(/Courtside Chocolate/gi))
			{
                if(obj.linked) var href = obj.server+'/showProductDetail.do?productId='+item.productId+'&catalogId=1';
                else var href = '#';
                listHTML +='<li><a href="'+href+'" class="bj_inner" alt="'+item.productDescription+'"><img src="'+obj.path+'images/bags/'+img+'" /><h4>'+pName+'</h4></a></li>';
            }
        });
		
		sliderHTML = '<div class="slider_left"></div><div class="slider"><div class="handle"></div></div><div class="slider_right"></div>';
		
		if(count > 5)
		{
			baseHTML+=sliderHTML;
		}
		
					
		if(jQuery("#bj_results").is(":hidden")) 
		{
			obj.enter(count, baseHTML, listHTML);
		}
		else
		{
			jQuery("#bj_results").fadeOut('slow',function(){
				obj.enter(count, baseHTML, listHTML);
			});
		}  
		
	
		  
	}
	
	this.enter = function(count, baseHTML, listHTML)
    {
        jQuery("#bj_results").empty().append(baseHTML);
				jQuery("#bj_results ul.items").append(listHTML);
                if(!obj.linked) jQuery("#bj_results ul.items li a").click(function(){return false;});
                if(count < 5) obj.centerList();
				obj.fixPng();
				jQuery("#bj_results").fadeIn('slow',function()
				{
					obj.animateDecision(count);
					obj.loader();
				});
    }

    this.centerList = function()
    {
            var container = jQuery('div.sliderGallery');
            var ul = jQuery('ul', container);
            var liOuter = 0;
            var liCount = 0;
            jQuery('.bj_inner').each(function(){
            	liCount += parseInt(jQuery(this).innerWidth());
                liOuter += parseInt(170);
            });
                var left = container.outerWidth()/2 - liOuter/2 - 20;
                ul.css('left',left);
    }
	
	this.fixPng = function()
	{
			jQuery("#bj_results img").ifixpng();
			jQuery("#bj_results div").ifixpng();
	}
	
	
	this.animateDecision = function(count){
	
			var container = jQuery('div.sliderGallery');
            var ul = jQuery('ul', container);
            var liOuter = 0; 
            var liCount = 0;
            jQuery('.bj_inner').each(function(){
            	liCount += parseInt(jQuery(this).innerWidth());
                liOuter += parseInt(jQuery(this).innerWidth()) + parseInt(jQuery(this).css('marginLeft'));
            });
            
            obj.createTooltip(".bj_inner");
            
            var itemsWidth = 20 + liOuter - container.outerWidth();
            
            if(count > 5)
            {
            $('.slider', container).slider({
                min: 0,
                max: itemsWidth,
                handle: '.handle',
                stop: function (event, ui) {
                    ul.animate({'left' : ui.value * -1}, 500);
                },
                slide: function (event, ui) {
                    ul.css('left', ui.value * -1);
                }
            });	
            }
           
	}
	
	this.createTooltip = function(el)
	{
		
		$(el).omnitip({
			prefix: 'readmore_',
			extraClass:'more', 
			travel:true, 
			travelDistance:50,
			animate:true,
			animationSpeed: 800,
			event:'mouseover',
			position:'bottom',
			contentAttribute:'alt'
		});		
	}

    this.loadGraphics = function()
    {
        var graphics = ['/x.png','/bg.jpg','/hd.png','/roastmenu.png','/tip/omnitip_topactive.png','/tip/omnitip_bottomactive.png','/tip/omnitip_bottom.png','/tip/omnitip_br.png','/tip/omnitip_bl.png','/tip/omnitip_body.gif','/tip/omnitip_top.png','/tip/omnitip_tr.png','/tip/omnitip_tl.png','/handle.png','/scroll.png','/scroll_right.png','/scroll_left.png']
        var op = obj.path + 'images';
        for(i=0;i<graphics.length;i++)
        {
            var img = new Image();
            img.src = op + graphics[i];
        }
    }
	
	//load external files 
	this.loadContent('bj_coffeefinder_min.css','bj_coffeefinder_css','css');
	//if(ieVer==6) this.loadContent('bj_coffeefinder_ie6.css','bj_coffeefinder_ie6_css','css');
	//if(!window.jQuery) {
		this.loadContent('jquery.b.min.js','jq','script'); //jquery only gets loaded if not already present
		obj.totalToLoad++;
		obj.loadCount++;
	//}
	//else
	//{
	//	obj.loadCount++;
	//}
	this.loadContent('jquery_plugins_min.js','jq_plugins','script');
	
	
}


