/*
 * 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 */
               
               
				/*
				 * handle search history
				 */
               SWFAddress.onInit = function() {
            	   bui.handleSWFAddressChange();
               };
               SWFAddress.onExternalChange = function() {
            	   bui.handleSWFAddressChange();
               };
          },
          
          handleSWFAddressChange : function() {
				
				var hash = SWFAddress.getValue();
				var SWFapp = hash.split('/')[1];
				
				// update if SWFapp changes
				if (SWFapp != '' && SWFapp != bui.currentSWFapp) {
					bui.currentSWFapp = SWFapp;
				}
				
				/*
				 * Search history
				 */
				if (bui.currentSWFapp == 'search') {

					// check for search parameter
					if (bui.getHashVar('q') != undefined && bui.getHashVar('q') != '/' && bui.getHashVar('q') != '') {
						app.suggest.display();
						app.suggest.acSearchField.val(bui.getHashVar('q'));
						app.suggest.suggest(bui.getHashVar('q'), 65);
					} else if (!jQuery('#search-global').hasClass('open')) {
						app.suggest.close();
					}
					
				} else {
					// cleanup
					if (!jQuery('#search-global').hasClass('open')) {
						app.suggest.close();
					}
				}
				
				/*
				 * Search refinements
				 */
				if (bui.currentSWFapp == 'refine') {

					// update grid with url
					if (hash != '' && hash != '/') {
						var refineUrl = window.location.pathname + '?' + hash.slice(hash.indexOf('?') + 1);
					} else {
						var refineUrl = window.location.href;
					}
					
					if (app.search != undefined) {
						app.search.result.updateGrid(refineUrl);
					}
				}
				
				/*
				 * Gear navigation (gender to root)
				 */
				if (bui.currentSWFapp == 'gear') {
					if (hash == '/') {
						jQuery('.back-to-root').click();
						
					} else if (hash != '/' && hash != '') {
						jQuery('#lb-overlay a[rel="' + bui.getHashVar('cgid') + '"]').click();
					}
				}
        	  
          },

          // @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');
               
               // set secondary nav link
               if (item !== undefined) {
                    if (item !== "cart") {
                         navLinks.removeClass('selected');
                         jQuery("a#" + item).addClass("selected");
                    }
               }
          },

          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();
                         }
                    });
               }
          },
          
          displaySwatches : function() {
      		var fold = jQuery(window).height() + jQuery(window).scrollTop() + 200;
      		jQuery('#search .productlisting .producttile').each(function() {
      			// Load if above the fold OR if mobile (no scroll callback)
      			if (jQuery(this).offset().top <= fold || navigator.userAgent.match(/mobile/i)) {
      				jQuery(this).find('.productSwatches').find('img.swatchImage').not('.loaded').each(function() {
      					var realSrc = jQuery(this).attr('new-src');
      					jQuery(this).hide().attr('src', realSrc);
      					jQuery(this).fadeIn().addClass('loaded');
      				});
      			}
      		});
          },

          // crossfade product images
          // Required: Images to be absolutely positioned
          crossFadeProductImages : function(imageSelector, newImageSrc, newAlt) {
               var newAlt = typeof (newAlt) !== 'undefined' ? newAlt : '';

               /*
               imageSelector.before('<img src="' + newImageSrc + '" alt="' + newAlt + '" title="' + newAlt + '" class="product new-image" style="z-index: 0;"/>');
               imageSelector.stop().fadeOut(175, function() {
                    imageSelector.parent().children('img.new-image').addClass('product').removeClass('new-image').css('z-index', 1);
                    imageSelector.not('.new-image').remove();
               });
               */
               imageSelector.attr('src', newImageSrc);
          },
          
          
          /*
           * 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;
          		  var vidUrl = 'http://gdata.youtube.com/feeds/api/videos/' + thisVideo._videoID + '?v=2&alt=jsonc&callback=?';
          	     jQuery.getJSON(vidUrl, function (data) {
          	    	if (!data.data)
          	    	{
          	    		log('bad video: ' + vidUrl);
          	    		return;
          	    	}
	          	    	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>")
						if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPod/i))) {
							window.location = _mLoc;
						}
					} else {
						jQuery('#' + thisVideo._targetDiv).html("<p>Sorry, the mobile version of this video is not available at this time.</p>")
					}
                   
                	// swfObject
                    if ((!navigator.userAgent.match(/iPhone/i)) && (!navigator.userAgent.match(/iPad/i)) && (!navigator.userAgent.match(/iPod/i))) {
    					var params = { 
							allowScriptAccess: 'always',
							wmode: 'transparent',
							allowFullScreen: 'true'
    					};
    	                var atts = { id: "_player" };

                        swfobject.embedSWF("http://www.youtube.com/v/" + thisVideo._videoID + "?enablejsapi=1&playerapiid=ytplayer&autohide=1&rel=0&fs=1&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');
	        	  }
        	  }
        	  
        	  bui.displaySwatches();
          },
          
          /*
           * add comment
           */
          sup : function() {
    			var regExp = new RegExp("[®]|\"","gi");
    			jQuery("body *").replaceText(regExp, '<sup>&reg;<\/sup>');
          }

     };
}(jQuery));

// application initialization on dom ready
jQuery(document).ready(function() {
     bui.init();
});

Date.prototype.formatDate = function(){ 
	var dd = this.getDate(); 
	if (dd < 10)
		dd='0'+dd; 
	var mm = this.getMonth()+1; 
	if(mm < 10)
		mm = '0' + mm; 
	var yyyy = this.getFullYear(); 
	return String(mm+"/"+dd+"/"+yyyy); 
}

Date.prototype.clearTime = function(){ 
	this.setHours(0,0,0,0);	
	return; 
}

function getMonthName(fdate){
	var date = new Date(fdate);
	var fmonth = date.getMonth()+1;
	var smonth = "";
	switch (fmonth){
	case 1: 
		smonth = "Jan";
		break;
	case 2: 
		smonth = "Feb";
		break;
	case 3: 
		smonth = "Mar";
		break;
	case 4: 
		smonth = "Apr";
		break;
	case 5: 
		smonth = "May";
		break;
	case 6: 
		smonth = "Jun";
		break;
	case 7: 
		smonth = "Jul";
		break;
	case 8: 
		smonth = "Aug";
		break;
	case 9: 
		smonth = "Sep";
		break;
	case 10: 
		smonth = "Oct";
		break;
	case 11: 
		smonth = "Nov";
		break;
	case 12: 
		smonth = "Dec";
		break;
	}
	return smonth;
}

function getDay(fdate){
	
	var sday = fdate.substring(3,4) != "0" ? parseInt(fdate.substring(3,5)) : parseInt(fdate.substring(4,5)) ;
	return sday;
}
