var rim = rim || {};

var devicePageLink = document.location.href.substring(0, document.location.href.indexOf('.jsp'));


if (devicePageLink.indexOf('curve') > -1 || devicePageLink.indexOf('pearl') > -1) {
	devicePageLink = devicePageLink + "3G"
}

if (document.location.href.indexOf('.jsp')>-1 && document.location.href.indexOf('index.jsp')>-1) {
	$($('#scrollerContent ul li')[0]).html($($('#scrollerContent ul li')[0]).html() + "<a href='" + devicePageLink + "/' class='devicePageMainLink'>&nbsp;</a>");
}

rim.OnloadEvents.Register(function () {
	var shareUrl = document.location.href;

	if (shareUrl.indexOf('?') > -1) {
		shareUrl = shareUrl.substring(0, shareUrl.indexOf('?'));
	}

	rim.PageModal.Register('shareMenu', rim.PageModal.DefaultUrl + '?modalid=shareMenu&url=' + shareUrl, null, rim.CenterModalOnLink, false);

	if (document.getElementById("buzz") != null) {
		var feedsUrl = 'torch.xml';

		if (typeof(deviceFeedsXmlUrl) != "undefined") {
			feedsUrl = deviceFeedsXmlUrl;
		}

		$("#buzz ul").remove();
		$("#buzz").append("<div id='feeds_body'></div>");
		parseXML(feedsUrl, $("#feeds_body"));
	}
});

rim.HeroScrollerFamily = function (selector) {

	this.WrapRight = false;
	this.WrapLeft= false;

	this.WrapBothClass = 'wrapBoth';
	this.WrapLeftClass = 'wrapLeft';
	this.WrapRightClass = 'wrapRight';

	this.ScrollerSelector = selector;
	this.Self = $(this.ScrollerSelector);

	this.StopPointSelector = '.stopPoint';
	this.StopPoints = $(this.StopPointSelector);

	this.ScrollLeftButton = $('#pageLeft');
	this.ScrollRightButton = $('#pageRight');

	this.PrevNameAttr = 'prevname';
	this.NextNameAttr = 'nextname';
	this.PrevUrlAttr = 'prevurl';
	this.NextUrlAttr = 'nexturl';

	this.OffsetAttr = 'offset';

	this.PrevNameDefault = '';
	this.NextNameDefault = '';

	this.CurrentIndex = 0;

	this.safeArea = 985;

	this.InitScroller();
};

rim.HeroScrollerFamily.prototype = {
	InitScroller: function () {

		$('#threeSixtyImage').live('mousedown', function() {
			doOmnitureUIEvent('360:NAV ACTION');
		});

		var me = this;

		var newLeft = ($(window).width() - 985)/2;

		newLeft = newLeft < 0? 0 : newLeft;

		var scroller = me.Self.find('ul:first');

		scroller.css({'left': newLeft + 'px', 'visibility': 'visible'});

		var scrollerLastLI = scroller.find('>li:not(#overscrollHelper):last');
        var scrollerWidth = scrollerLastLI.width() + scrollerLastLI.position().left + newLeft;
        scroller.width(scrollerWidth);

		$('.scroller .replace').css({ visibility: 'visible' });

		$('#pageLeft').css({ visibility: 'visible' });
		$('#pageRight').css({ visibility: 'visible' });

		if (me.Self.parent().hasClass(me.WrapBothClass)){
			me.WrapRight = true;
			me.WrapLeft = true;
		}

		if (me.Self.parent().hasClass(me.WrapRightClass)){
			me.WrapRight = true;
		}

		if (me.Self.parent().hasClass(me.WrapLeftClass)){
			me.WrapLeft = true;
		}

		var appTooltipTemplate = '<div><div role="appTooltip"></div></div>';
		$('.embed-application-tooltip').each(function() {
			var tip = new Rf.EmbeddedTooltip(this, '.application-tooltip-content', {
				ID : 'MyAppTooltip',
				ClassName : 'appTooltip',
				Template : appTooltipTemplate
			}).WatchHover(250)
			  .WatchFocus(250);

		    tip.Bind(Rf.Tooltip.Events.Show, function(element, event) {
		    	$('.appTooltip .title').addClass('replace');
		    	$('.appTooltip .price').addClass('replace');
		    	rim.InitCufon();
		    });
		});

		$(document).bind('keydown', function (e) {
			switch(e.keyCode) {
			case 37://left

				if(me.CurrentIndex > 0){
					me.SlideLeft();
				}
				break;
			case 39://right
				if(me.CurrentIndex < (me.StopPoints.length - 1)){
					me.SlideRight();
				}
				break;
			}
		});
		var overscrollHelper = null;
		if(!scroller.find('#overscrollHelper').length){
            scroller.append('<li id="overscrollHelper">&nbsp;</li>');
            $('#overscrollHelper').css({
                width: '100%',
                height: '100%',
                position: 'absolute',
                top: '0px',
                left: '0px',
                zIndex: '99999999',
                display: 'none'
            });
            overscrollHelper = $('#overscrollHelper');
        }else{
            overscrollHelper = $('#overscrollHelper');
        }
		me.Self.overscroll({direction:'horizontal', showThumbs: false, openedCursor: '/assets_refresh/images/opened.cur',closedCursor: '/assets_refresh/images/closed.cur', onDriftStart: function(){
            overscrollHelper.show();
            if ($.browser.msie) {
                document.selection.empty();
            }
            $(this).disableTextSelect();
            if (!me.ScrollLeftButton.is('.inactive')) me.ScrollLeftButton.addClass('inactive');
            if (!me.ScrollRightButton.is('.inactive')) me.ScrollRightButton.addClass('inactive');
        }, onDriftEnd: function(){
            overscrollHelper.hide();
            var currentItem = $('ul.scroller > li.stopPoint:in-viewport:first');
            me.StopPoints.each(function(i) {
                if ($(this).attr('id') == currentItem.attr('id')) {
                    me.CurrentIndex = i;
                    me.UpdateScrollButtons();
                };
            });
            $(this).enableTextSelect();
            if (!me.ScrollLeftButton.is('.inactive')) me.ScrollLeftButton.removeClass('inactive');
            if (!me.ScrollRightButton.is('.inactive')) me.ScrollRightButton.removeClass('inactive');
        }});

		me.InitScrollerNav();

		me.Self.show();

	},
	/* level studios modification: start */
	LoadVideo: function(embedCode, xmlPathUrl) {
		var lightBox = $('#videoLightbox');
		if (typeof(xmlPathUrl) == "undefined") {
			doOmnitureVideoEvent(embedCode);

			if (!document.getElementById('videoLightbox')) {
				$('#heroScroller').append("<div id='videoLightbox'><a href='javascript:hScroller.CloseVideo();'>&nbsp;</a>" + embedCode + "</div>");
				lightBox = $('#videoLightbox');
			} else {
				lightBox.html("<a href='javascript:hScroller.CloseVideo();'>&nbsp;</a>" + embedCode);
			}
		} else {
			doOmnitureVideoEvent(xmlPathUrl);

			if (!document.getElementById('videoLightbox')) {
				var parent = $('#detailsFlash')
				if (!document.getElementById('detailsFlash')) {
					parent = $('#scrollerContent');
				}
				parent.append("<div id='videoLightbox'><a href='javascript:hScroller.CloseVideo();'>&nbsp;</a><div id='flashMovieReplace'>&nbsp;</div></div>");
				lightBox = $('#videoLightbox');
			} else {
				lightBox.html("<a href='javascript:hScroller.CloseVideo();'>&nbsp;</a><div id='flashMovieReplace'>&nbsp;</div>");
			}

			var variables = { xmlPath: xmlPathUrl, configPath: rim.lang.rootPath+"assets/flash/config.xml", vidwidth:640, vidheight:387, pageid:1, defaultid:1, autoplay:"false", controls:"static" };
			var params = {
				allowFullScreen: true,
				allowScriptAccess: "always",
				bgcolor: "#000000",
				scale: "noscale",
				salign: "TL"
			};
			swfobject.embedSWF(rim.lang.rootPath+"assets/flash/videoPlayer.swf", "flashMovieReplace", "640", "387", "9", null, variables, params);

			lightBox.addClass('smallFlashVideo');
		}

		lightBox.css('display', 'block');

		var scroll = window.pageYOffset;

		if (document.all) {
			scroll = document.body.scrollTop;
		}

		lightBox.css('top', (62 + scroll) + 'px');

		$('#detailsContent').live('click', function(e) {
			hScroller.CloseVideo();
		});
	},
	CloseVideo: function() {
		var lightBox = $('#videoLightbox');
		lightBox.css('display', 'none');
		lightBox.html('&nbsp;');
	},

	InitScrollerNav: function () {
		var me = this;

		me.UpdateScrollButtons();

		me.ScrollLeftButton.add(me.ScrollRightButton).hover(
			function () {
				var button = $(this);
				if (button.is('.inactive')) return;
				$(this).find('.hoverText em').show();
			},
			function () {
				var button = $(this);
				if (button.is('.inactive')) return;
				$(this).find('.hoverText em').hide();
			}
		);
	},
	GetNewLeft: function(index){
		var me = this;

		var currentSlide = $(me.StopPointSelector + ":eq(" + index + ")");

		var offset = currentSlide.attr(me.OffsetAttr);

		if(!offset){
			offset = 0;
		} else {
			offset = parseInt(offset);
		}

		var windowWidth = $(window).width();

		//return  (currentSlide.position().left * -1) + ((windowWidth - me.safeArea) / 2) - offset;
		return  (currentSlide.position().left);
	},
	UpdateScrollButtons: function () {
		var me = this;

		var currentSlide = $(me.StopPointSelector + ":eq(" + me.CurrentIndex + ")");

		var showPrev = true;

		var showNext = true;
        if(document.location.href.indexOf('.jsp')==-1 || document.location.href.indexOf('index.jsp')>-1){
            if(!me.WrapLeft && me.CurrentIndex == 0) {
    		 			showPrev = false;
    		}
        }


		if((typeof(scrollerDontWrap) != "undefined" || typeof(scrollerDontWrapRight) != "undefined") && me.CurrentIndex == (me.StopPoints.length - 1)) {
			showNext = false;
		}

		if((typeof(scrollerDontWrap) != "undefined" || typeof(scrollerDontWrapLeft) != "undefined") && me.CurrentIndex == 0) {
			showPrev = false;
		}

		var prevName = currentSlide.attr(me.PrevNameAttr);

		var prevUrl = currentSlide.attr(me.PrevUrlAttr);

		var nextName = currentSlide.attr(me.NextNameAttr);

		var nextUrl = currentSlide.attr(me.NextUrlAttr);
        //console.log(nextUrl)
		if(!prevName){
			prevName = me.PrevNameDefault;
		}

		if(!nextName){
			nextName = me.NextNameDefault;
		}

		if(!prevUrl){
			me.ScrollLeftButton.unbind('mouseup').bind('mouseup', function (event) {
				event.preventDefault();
				if ($.browser.msie || $.browser.webkit) {
				    setTimeout("hScroller.SlideLeft();", 10);
				    return false;
				}else{
				    $(this).delay(10);
				    me.SlideLeft();
				}
			});
			me.ScrollLeftButton.attr("href", "#");
		} else {
			me.ScrollLeftButton.unbind('mouseup');
		}

		if(!nextUrl){
			me.ScrollRightButton.unbind('mouseup').bind('mouseup', function (event) {
				event.preventDefault();
			    if ($.browser.msie || $.browser.webkit) {
				    setTimeout("hScroller.SlideRight();", 10);
				    return false;
				}else{
				    $(this).delay(10);
				    me.SlideRight();
				}
			});
			me.ScrollRightButton.attr("href", "#");
		} else {
			me.ScrollRightButton.unbind('mouseup');
		}
		if(showPrev){
			me.ScrollLeftButton.removeClass('inactive');
			me.ScrollLeftButton.find('.hoverText em').html(prevName);
			me.ScrollLeftButton.attr("href",prevUrl);
		} else {
			me.ScrollLeftButton.addClass('inactive');
		}

		if(showNext){

			me.ScrollRightButton.removeClass('inactive');
			me.ScrollRightButton.find('.hoverText em').html(nextName);
			me.ScrollRightButton.attr("href",nextUrl);
		} else {
			me.ScrollRightButton.addClass('inactive');
		}

	},
	SlideLeft: function(){
		doOmnitureUIEvent('nav - left');

		var me = this;

		var jump = false;

		me.CurrentIndex--;
		if (me.CurrentIndex < 0){
			jump = true;
			me.CurrentIndex = me.StopPoints.length - 1;
		}

		omnitureArrowClick('left');

		me.ScrollTo(jump);


	},
	SlideRight: function(){
		doOmnitureUIEvent('nav - right');

		var me = this;

		var jump = false;

		me.CurrentIndex++;

		if (me.CurrentIndex >= me.StopPoints.length){

			jump = true;

			me.CurrentIndex = 0;

		}

		omnitureArrowClick('right');

		me.ScrollTo(jump);

	},
	ScrollTo: function (jump){
		var me = this;

		me.ScrollLeftButton.addClass('inactive');
		me.ScrollRightButton.addClass('inactive');

		var newLeft = me.GetNewLeft(me.CurrentIndex);

		var scroller = me.Self.find('ul:first');

		if(jump){
			//scroller.css('left', newLeft + 'px');
            me.Self.scrollLeft(newLeft);
		} else {
			//scroller.animate({left:newLeft}, {duration:500, easing:'easeInOutQuad', complete:lastly});
			/*scroller.animate({
			    left: newLeft
			  }, 1800);*/

              me.Self.animate({
  			    scrollLeft: newLeft
  			  }, 1800);

		}

		me.UpdateScrollButtons();
	}
};

var hScroller;

rim.OnloadEvents.Register(function () {
	hScroller = new rim.HeroScrollerFamily('#scrollerContent');
});

