//------------------------------------------------------------------------------------
// Carousel
(function($) {
$.fn.gdeCarousel = function(o) {
    o = $.extend({
		start: 0,
		move: 5,		
		display: 5,
		vertical: false,
		speed: 400,
		loop: true,
		easing: null,
		btnPrev: null,
		btnNext: null,
		pageNav: true,
		preAction: null,
		postAction: null
    }, o || {});

    return this.each(function() {
		var div = $(this), ul = $("ul", div), lis = $("li", ul), lit = lis.size(), d = o.display;
		div.parent().css("display", "block");
		trackingEvent('carousel');
		//var running = false;
		var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
		
		
		var pages = Math.ceil(lit/d);

		$.each($("li", ul), function(index) {
			var pos = index+1;
			var page = Math.ceil(pos/d);
			var pagePos = pos-(d*page)+d;
			var id = div.parent().attr('class').split(' ')[0];
			$("a", this).attr('name', "&lid="+id+":"+page+"_"+pagePos+"_"+this.id+"&lpos=sitesearch:"+id+":"+page+"_"+pagePos);
		});

		
        if(o.loop) {
			//if(lit > d){
				ul.prepend(lis.slice(lit-d-1+1).clone())
				  .append(lis.slice(0,d).clone());
				o.start += d;
			//}
		}
	
        var li = $("li", ul), itemLength = li.size(), totalItems = itemLength-(d*2), pos = o.start;

		
		li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
        //li.css({float:"left", overflow: "hidden"});
        ul.css({position: "relative", margin: "0", padding: "0", "list-style-type": "none", "z-index": "1"});
        div.css({position: "relative", overflow: "hidden", left: "0px", "z-index": "2"});

		
		var liWidth = o.vertical ? height(li) : width(li);
        //var liWidth = width(li);
        var ulWidth = liWidth * itemLength;
        var divWidth = liWidth * d;

        li.css({width: li.width()});
        //ul.css("width", ulWidth+"px").css("left", -(pos*liWidth));
		ul.css(sizeCss, ulWidth+"px").css(animCss, -(pos*liWidth));
		
        //div.css("width", divWidth+"px");
		div.css(sizeCss, divWidth+"px");
				
		var navDiv = document.createElement('div');
		navDiv.className = 'carouselNav';

		if(o.pageNav && lit>d){
			for(var i=1;i<pages+1;i++){
				var link = document.createElement('a');
				if(i==1){
					link.className = ((i*d)-d+1)+" active";
				} else {
					link.className = (i*d)-d+1;
				}
				link.setAttribute('href', '#');
				link.setAttribute('title', 'Page '+i);
				//link.setAttribute('name', '');
				navDiv.appendChild(link);
			
				link.onclick = function (){
					var c = this.className-1;
					scrollTo(o.loop ? o.display+c : c);
					return false;
				};
				navDiv.appendChild(link);
			}
			div.parent().append(navDiv);
		}
		
		//alert("lit: "+lit+" | d: "+d);
		if(lit<=d){
			
			$(o.btnPrev).css({visibility: 'hidden'});
			$(o.btnNext).css({visibility: 'hidden'});
		}
        if(o.btnPrev)
			if(!o.loop) {
				$( (pos-o.move<0 && o.btnPrev) ).addClass("disabled");
			}
				
            $(o.btnPrev).click(function() {
                return scrollTo(pos-o.move);
            });

        if(o.btnNext)
            $(o.btnNext).click(function() {
                return scrollTo(pos+o.move);
            });

        function vis() {
            return li.slice(pos).slice(0,d);
        };

        function scrollTo(target) {
            if(!running && !isNaN(target)) {

                if(o.preAction)
                    o.preAction.call(this, vis());
                if(o.loop) {
                    if(target<=o.start-d-1) {
						ul.css(animCss, -((itemLength-(d*2))*liWidth)+"px");
                        pos = target==o.start-d-1 ? itemLength-(d*2)-1 : itemLength-(d*2)-o.move;
                    } else if(target>=itemLength-d+1) {
						ul.css(animCss, -( (d) * liWidth ) + "px" );
                        pos = target==itemLength-d+1 ? d+1 : d+o.move;
                    } else { 
						pos = target;
					}
                } else {
                    if(target<0 || target>=itemLength) return;
                    else pos = target;
                }       

                running = true;

				if(o.pageNav && lit>d){
					$('.active',div.parent()).removeClass("active");
				}
                ul.animate(
					animCss == "left" ? { left: -(pos*liWidth) } : { top: -(pos*liWidth) } , o.speed, o.easing,
                    function() {
						if(o.pageNav && lit>d){
							if(o.loop) {
								if(pos >totalItems){
									$('.'+1, div.parent()).addClass('active');
								} else if (pos < 1) {
									$('.'+(totalItems-d+1), div.parent()).addClass('active');
								} else {
									$('.'+(pos-d+1), div.parent()).addClass('active');
								}
							} else {
								$('.'+(pos+1), div.parent()).addClass('active');
							}
						}
						
                        if(o.postAction){
                            o.postAction.call(this, vis());
						}
                        running = false;
                    }
                );

                if(!o.loop) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (pos-o.move<0 && o.btnPrev) || (pos+o.move >= itemLength && o.btnNext) ).addClass("disabled");
                }
            }
            return false;
        };
    });
};

})(jQuery);


//------------------------------------------------------------------------------------
// Tooltip
(function($) {
    $.fn.gdeToolTip = function(options) {
        options = $.extend({}, $.fn.gdeToolTip.defaults, options);
        return this.each(function() {
            var o = $.fn.gdeToolTip.elementOptions(this, options);
            $(this).hover(function() {
                $.data(this, 'cancel.gdeToolTip', true);

                var tip = $.data(this, 'active.gdeToolTip');

                if (!tip) {
                    tip = $('<div class="gdeToolTip"><div class="gdeToolTip-inner"/></div>');
                    tip.css({position: 'absolute', zIndex: 100000004});
                    $.data(this, 'active.gdeToolTip', tip);
                }

                if ($(this).attr('title') || typeof($(this).attr('original-title')) != 'string') {
                    $(this).attr('original-title', $(this).attr('title') || '').removeAttr('title');
                }

                var title;
                if (typeof o.title == 'string') {
                    title = $(this).attr(o.title == 'title' ? 'original-title' : o.title);
                } else if (typeof o.title == 'function') {
                    title = o.title.call(this);
                }

                tip.find('.gdeToolTip-inner')['html'](title || o.generic);

                var pos = $.extend({}, $(this).offset(), {width: this.offsetWidth, height: this.offsetHeight});
                tip.get(0).className = 'gdeToolTip';

				if(isNotBlank(o.css)){
					tip.addClass(o.css);
				}
				
                tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
                var actualWidth = tip[0].offsetWidth, actualHeight = tip[0].offsetHeight;
                var orient = (typeof o.orient == 'function') ? o.orient.call(this) : o.orient;

				
                switch (orient) {
                    case 'left':
                        tip.css({top: pos.top + o.offsetY + pos.height / 2 - actualHeight / 2, left: pos.left - o.offsetX - actualWidth}).addClass('gdeToolTip-right');
                        break;
					case 'right':
                        tip.css({top: pos.top + o.offsetY + pos.height / 2 - actualHeight / 2, left: pos.left + o.offsetX + pos.width}).addClass('gdeToolTip-left');
                        break;
                    case 'top':
                        tip.css({top: pos.top - o.offsetY - actualHeight, left: pos.left + o.offsetX + pos.width / 2 - actualWidth / 2}).addClass('gdeToolTip-bottom');
                        break;
					case 'bottom':
                        tip.css({top: pos.top + o.offsetY + pos.height, left: pos.left + o.offsetX + pos.width / 2 - actualWidth / 2}).addClass('gdeToolTip-top');
                        break;
                }

				if(title.length>0){
					if (o.fade) {
						tip.css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: 1},400);
					} else {
						tip.css({visibility: 'visible'});
					}
				}

            }, function() {
                $.data(this, 'cancel.gdeToolTip', false);
                var self = this;

				if ($.data(this, 'cancel.gdeToolTip')) return;
				var tip = $.data(self, 'active.gdeToolTip');
				if (o.fade) {
					tip.stop().fadeOut(100,function() { $(this).remove(); });
				} else {
					tip.remove();
				}


            });
            
        });
        
    };
    
    $.fn.gdeToolTip.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };
    
    $.fn.gdeToolTip.defaults = {
		offsetX: 0,
		offsetY: 0,
		title: 'title',
		orient: 'top',
		generic: '',
		css: '',
		fade: false
    };

    $.fn.gdeToolTip.autoLeftRight = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'left' : 'right';
    };    
    $.fn.gdeToolTip.autoTopBottom = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 'top' : 'bottom';
    };
        
})(jQuery);



//------------------------------------------------------------------------------------
// Carousel Tooltip
function getCarouselTipData(){
	title = this.getAttribute('header');
	description = this.getAttribute('description');
	description= description.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
	meta = this.getAttribute('meta');
	rating = this.getAttribute('rating');
	productcategoryname = this.getAttribute('productcategoryname');
	
	if(isNotBlank(title)) title = "<div class='gdeToolTipTitle'>"+title+"</div>";
	else title = '';
		
	if(!isNotBlank(description)) description = '';
	
	
	if(isNotBlank(productcategoryname)){
		productcategoryname = "<div class='gdeToolTipCategory'>"+productcategoryname+"</div>";
	} else {
		if(isNotBlank(rating) && !isNaN(rating)){
			productcategoryname = "<div class='gdeToolTipCategory'> </div>";
		} else {
			productcategoryname = '';
		}
	}
	
	if(isNotBlank(rating) && !isNaN(rating)){
		var w = (87/5)*rating;
		rating = "<div class='gdeToolTipRating'><div class='gdeToolTipRatingStars' style='width:"+w+"px'></div></div>";
	} else {
		rating = '';
	}
	
	
	if(isNotBlank(meta)) meta = "<div class='gdeToolTipMeta'>"+meta+"</div>";
	else meta = '';
	
	//var tipDisplay = title+description+" "+this.getAttribute('rating')+" "+productcategoryname+rating+meta;
	var tipDisplay = title+description+meta+productcategoryname+rating;

	return tipDisplay;
}


//------------------------------------------------------------------------------------
// Build Module based on returned JSON data
function buildModule(index, item){
	switch (item.type) {
		case 'carousel':
			buildCarouselData(index,item);
			break;
	}
}


//------------------------------------------------------------------------------------
// Build Carousel Data
function buildCarouselData(index, item){
	var display = item.display;
	var totalItems = item.results.length;
	if(totalItems > 0){
		var carouselId = '.'+item.id;

		var prevNav = document.createElement('a');
		prevNav.className = 'scrollButton prevNav';
		prevNav.setAttribute('href', '#');
		prevNav.setAttribute('onclick', 'return false');

		var carouselContents = document.createElement('div');
		carouselContents.className = 'carouselContents';

		var carouselUl = document.createElement('ul');
		carouselContents.appendChild(carouselUl);
		
		var nextNav = document.createElement('a');
		nextNav.className = 'scrollButton nextNav';
		nextNav.setAttribute('href', '#');
		nextNav.setAttribute('onclick', 'return false');
		
		$(carouselId).append(prevNav);
		$(carouselId).append(nextNav);
		$(carouselId).append(carouselContents);
		
		$.each(item.results, function(index) { 
			var li = document.createElement('li');
			li.className = 'carouselItem';
			li.setAttribute('header', this.header);
			li.setAttribute('description', this.description);
			li.setAttribute('rating', this.rating);
			li.setAttribute('productcategoryname', this.productcategoryname);
			li.setAttribute('meta', this.meta);
			li.id = this.cmsid;
			
			var img = document.createElement('img');
			img.setAttribute('src', this.thumb);
			var br = document.createElement('br');
			var a = document.createElement('a');
			a.setAttribute('href', this.url);
			var txt = document.createTextNode(this.header);
			var textContainer = document.createElement('div');
			textContainer.className = 'carouselItemLabel';
			textContainer.appendChild(txt);
			
			li.appendChild(a);
			a.appendChild(img);
			a.appendChild(br);
			a.appendChild(textContainer);
			
			carouselUl.appendChild(li);
		});
	}

	if(totalItems%display){
		var offset = display-(totalItems%display);
		for(var i = 0;i<offset;i++){
			
			var li = document.createElement('li');
			li.className = 'carouselItem spacer';
			var txt = document.createTextNode('.');
			li.appendChild(txt);
			carouselUl.appendChild(li);
		}
	}

}
		

//------------------------------------------------------------------------------------
// Utility Functions

function width(e) {
    return  e[0].offsetWidth + css(e, 'marginLeft') + css(e, 'marginRight');
};
function height(e) {
    return e[0].offsetHeight + css(e, 'marginTop') + css(e, 'marginBottom');
};

function css(e, p) {
    return parseInt($.css(e[0], p)) || 0;
};

function isNotBlank(v){
	r = true;
	if(v == null || v == '' || v == undefined || v == 'null' || v == 'undefined'){
		r = false;
	};
	return r;
};

function trackingEvent(e) {
	try{
		cto.engagementType=e;
		cto.trackEvent();
		cto.engagementType="";
	}
	catch(e){}
};

