/*
 * BURTON UI tools independent of app
 *
 * The code relies on the jQuery JS library to
 * be also loaded.
 */

var bui = (function(jQuery) {

     if (!jQuery) {
          alert("jQuery is not loaded yet!");
          return null;
     }

     return {
          URLs : {},
          currentSWFapp : '',
          
          init : function() {

               bui.setNav();
                              
               jQuery("img.swapImage").livequery(function(){ 
              // use the helper function hover to bind a mouseover and mouseout event 
                  jQuery(this) 
                      .hover(function() { 
                           src = src.replace("-off","-on");
                      }, function() { 
                           src = src.replace("-on","-off");
                      }); 
              }, function() { 
                  // unbind the mouseover and mouseout events 
                  jQuery(this) 
                      .unbind('mouseover') 
                      .unbind('mouseout'); 
              }); 
               
               
               /* LOOKBOOK/VIEW ON RIDER FUNCTION */
                 jQuery("#lookbook_image,#lookbook_imagehover,#lookbook_texthover").live("mouseover mouseout", function(event) {
                      if(event.type === "mouseover") {
                           jQuery("#lookbook_imagehover,#lookbook_texthover").show(); 
                      }
                      else {
                           jQuery("#lookbook_imagehover,#lookbook_texthover").hide(); 
                      }
               });                   

               jQuery("#lookbook_right, #lookbook_left").live('click', function() {
                    if (id === "lookbook_right") {
                         imgNum ++;
                    } else if (id === "lookbook_left") {
                         imgNum --;
                    }

                    if (lookbookimgs !== null) {
                         if (imgNum > lookbookimgs.length-1) {
                              imgNum = 0;
                         } else if (imgNum <0) {
                              imgNum = lookbookimgs.length-1;
                         }
                         loadImage(imgNum);
                    }
               });
               
               /* END: LOOKBOOK/VIEW ON RIDER FUNCTION */
               
               
          },

          // @param - anchors to display within backtotop menu
          // anchors: {
          // "#sidebar-cat": "Filter Products"
          // }
          backToTop : function(options) {
        	  /*
        	   * REMOVE
        	   */
          },
          
          /*
           * Accepts a ul#selector with same-page anchor children nav
           */
          scrollPage: function(parent) {
        	  jQuery(parent).find('a').click(function() {
                  var thisHref = jQuery(jQuery(this).attr('href'));
                  jQuery(window).scrollTo(thisHref, 500);
        		  return false;
        	  });
          },
          
          scrollTip: function() {
        	  
          },

          setNav : function(item) {
               navLinks = jQuery('#primarynav a, #secondarynav a');
               
               // set secondary nav link
               if (item !== undefined) {
                    if (item !== "cart") {
                         navLinks.removeClass('active');
                         jQuery("a#" + item).addClass("active");
                    }
               } else {
                    // auto set secondary nav link
                    var loc = window.location.pathname+window.location.search;
                   navLinks.each(function() {
                        if (window.location.href.indexOf(loc) !== -1 && !jQuery('body').hasClass('default-start')) {
                            jQuery(this).addClass('active');
                       }
                   });
               }
               // set primary nav link
               jQuery('#' + jQuery('#secondarynav #subHeader .categorymenu ul').attr('rel')).addClass('active');
          },

          setSelectedNav : function(id) {
               jQuery('#'+id).find('a').removeClass('selected');
             var curUrl = window.location.href;
             curUrl = curUrl.substring(curUrl.lastIndexOf('/'));
               jQuery('#'+id).find('a[href$="' + curUrl + '"]').addClass('selected');
          },

          setCookie : function(cookieName, value, expiredays) {
               var exdate = new Date();
               exdate.setDate(exdate.getDate() + expiredays);
               document.cookie = cookieName
                         + "=" + escape(value)
                         + ((expiredays === null) ? "" : ";expires=" + exdate.toGMTString());
          },

          setCookieWithPath : function(cookieName, value, expiredays, path) {
               var exdate = new Date();
               exdate.setDate(exdate.getDate() + expiredays);
               document.cookie = cookieName
                         + "="
                         + escape(value)
                         + ";"
                         + ((path) ? "path=" + path : "")
                         + ((expiredays === null) ? "" : ";expires="
                         + exdate.toGMTString());

          },

          getCookie : function(cookieName) {
               if (document.cookie.length > 0) {
                    c_start = document.cookie.indexOf(cookieName + "=");
                    if (c_start !== -1) {
                         c_start = c_start + cookieName.length + 1;
                         c_end = document.cookie.indexOf(";", c_start);
                         if (c_end === -1) {
                              c_end = document.cookie.length;
                         }
                         return unescape(document.cookie.substring(c_start, c_end));
                    }
                    return "";
               }
          },

          // get JSON format cookie
          getJSONCookie : function(cookieName) {
               var cookieData = bui.getCookie(cookieName);
               return cookieData ? jQuery.parseJSON(cookieData) : {};
          },

          // set JSON format cookie
          setJSONCookie : function(cookieName, data, expiredays) {
               var cookieData = '';

               if ((typeof data !== 'object') && !(data instanceof Array)
                         && (data !== null)) { // data must be a true object to be
                                                       // serialized
                    throw new Error('JSONCookie data must be an object');
               }

               cookieData = JSON.stringify(data);
               return bui.setCookie(cookieName, cookieData, expiredays);
          },

          // sets fixed equal height for group of selectors
          equalHeight : function(group) {
               tallest = 0;
               group.each(function() {
                    thisHeight = $(this).height();
                    if (thisHeight > tallest) {
                         tallest = thisHeight;
                    }
               });
               group.height(tallest);
          },
          
          // sets fixed equal width for group of selectors
          equalWidth : function(group) {
               widest = 0;
               group.each(function() {
                    thisWidth = $(this).width();
                    if (thisWidth > widest) {
                         widest = thisWidth;
                    }
               });
               group.width(widest);
          },
          
          // sets fixed equal height for group of selectors, the first selector is the basis of the height
          sameHeight : function(first, second) {
               jQuery(second).height(jQuery(first).height());
          },

          updateUserDataInHeader : function() {
               // unfortunately the two subsequent calls collide! If i put them
               // just one after
	          // the other, only the first one will be executed :-((
	          jQuery("div${'#'}minicart").load("${URLUtils.url('Cart-MiniCart')}",null,function(response) {
	               jQuery("div${'#'}minicart").html(response);
	               jQuery("div.headercustomerinfo").parent().load("${URLUtils.url('Home-IncludeHeaderCustomerInfo')}");
	          });
	     },

	     // get url vars
          getUrlVars : function(hashString) {
               var vars = [], hash;
               
               if (typeof hashString === 'undefined') {
            	   var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
               } else {
            	   var hashes = hashString.slice(hashString.indexOf('?') + 1).split('&');
               }
               var i;
               for ( i = 0; i < hashes.length; i++) {
                    hash = hashes[i].split('=');
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
               }
               return vars;
          },

          // get url var
          getUrlVar : function(name) {
               return bui.getUrlVars()[name];
          },
          
          getHashVar : function(name) {
        	  return bui.getUrlVars(SWFAddress.getValue())[name];
          },

          // bind lazyload to productlistings (called from various places)
          lazyloadProducts : function(name) {
               var productTileSelector;
               if (name !== undefined) {
                    productTileSelector = jQuery("#search " + name + " .productImage img");
               } else {
                    productTileSelector = jQuery("#search .producttile .productImage img");     
               }

               if (app.productlazyload !== "load") {
                    productTileSelector.lazyload({
                         placeholder : bui.URLs.lazyloadPlaceholder,
                         effect : "fadeIn"
                    });
               }
               
               if (name !== undefined) {
                    jQuery("#search .product").removeClass('product-new');
               }
          },
          
          // fires callback when below the fold scrolls into focus
          // @param - element - element to come into focus
          // @param - threshold - fine tune offset when the callback fires
          belowTheFold : function(options, callback) {
               var fold = 0;
               var firedFlag = false;
               if (!options.threshold) {
                    options.threshold = 50;
               }
               var elementOffest = jQuery(options.element).offset().top - options.threshold;
               
               if (options.element && callback !== undefined) {
                    jQuery(window).scroll(function() {
                         fold = jQuery(window).height() + jQuery(window).scrollTop();
                         if (fold >= elementOffest && !firedFlag) {
                              firedFlag = true;
                              callback();
                         }
                    });
               }
          },

          // crossfade product images
          // Required: Images to be absolutely positioned
          crossFadeProductImages : function(imageSelector, newImageSrc, newAlt) {
               newAlt = typeof (newAlt) !== 'undefined' ? newAlt : '';

               imageSelector.before('<img src="' + newImageSrc + '" alt="' + newAlt + '" title="' + newAlt + '" class="new-image" style="z-index: 0;"/>');
               imageSelector.fadeOut(175, function() {
                    imageSelector.parent().find('img.new-image').addClass('product').removeClass('new-image').css('z-index', 1);
                    // jQuery(this).remove();
               });
               // imageSelector.attr('src', newImageSrc).attr('alt', newAlt);
          },
          
          
          /*
           * YouTube Video Handling
           */
          youTubeVideo : {

        	  _description : '',
        	  _title : '',
        	  _fullLoc : '',
        	  _poster : '',
        	  _auto : false,
        	  
        	  init: function(options) {
        	  		var thisPlayer = this;
        	  
        	  		thisPlayer._options = options;
        	  		thisPlayer._videoID = options[0];
        	  		thisPlayer._targetDiv = options[1];
        	  		thisPlayer._videoWidth = options[2];
        	  		thisPlayer._videoHeight = options[3];
        	  		thisPlayer._autoPlay = options[4];
					
	        	  if (options[5] != null){
	        		  thisPlayer._callBack = options[5];
	        	  }
	        	  
	        	  thisPlayer.getYoutubeData();
        	  },
          	  
        	  getYoutubeData : function () {
          		  
          		  var thisVideo = this;
          		  
          	     jQuery.getJSON('http://gdata.youtube.com/feeds/api/videos/' + thisVideo._videoID + '?v=2&alt=jsonc&callback=?', function (data) {
          	    	
          	    	thisVideo._description = data.data.description;
          	    	thisVideo._title = data.data.title;
          	    	thisVideo._fullLoc = data.data.player;

					var _mLoc;
					if( data.data.content[5] != null){
						_mLoc = data.data.content[5];
					} else if(data.data.content[6]!= null) {
						_mLoc = data.data.content[6];
					}
					var _poster = data.data.thumbnail.hqDefault;
					if (_mLoc!=null) {
						jQuery('#' + thisVideo._targetDiv).html("<a href='"+ _mLoc+"'><img src='"+_poster+"'  width='"+ thisVideo._videoWidth +"' height='"+ thisVideo._videoHeight +"' ></img></a>")
					} else {
						jQuery('#' + thisVideo._targetDiv).html("<p>Sorry, the mobile version of this video is not available at this time.</p>")
					}
					var params = { 
						allowScriptAccess: 'always',
						wmode: 'transparent',
						allowFullScreen: 'true'
					};
                    var atts = { id: "_player" };
                   
                   // swfObject
                   swfobject.embedSWF("http://www.youtube.com/e/" + thisVideo._videoID + "?enablejsapi=1&playerapiid=ytplayer&autohide=1&rel=0&autoplay=" + thisVideo._autoPlay, thisVideo._targetDiv, thisVideo._videoWidth, thisVideo._videoHeight, '8', null, null, params, atts);
                   
                   // callback
                   if (thisVideo._callBack) {
                	   thisVideo._callBack(thisVideo._videoID, thisVideo._title, thisVideo._description);	
                   }	
          	     });
          	  },
	    	  
          	  hide : function (options) {
          		  var _targetDiv = this;
          		  jQuery(_targetDiv).html("<div id='_player'/>");
          	  },
          	  
          	  update : function (_newID) {
        				
          	  }
          	  
          },
          
            /*
	  		*	set fixed menu
	  		*/
          checkScrollHeight : function(fixedHeader) {
        	  app.search.scrollHeight = jQuery(window).scrollTop();
        	  
        	  if (fixedHeader == true) { 
	        	  var headerHeight = jQuery('#header').height();
	        	  if (app.search.scrollHeight >= headerHeight) {
	        		  jQuery('#wrapper').addClass('fixed');
	        	  } else if (app.search.scrollHeight < headerHeight) {
	        		  jQuery('#wrapper').removeClass('fixed');
	        	  }
        	  }
          }

     };
}(jQuery));

// application initialization on dom ready
jQuery(document).ready(function() {
     bui.init();
});
