/*
 * Toggles 'over' class on parent element.
 */
(function($){  
	$.fn.toggleOverClassToParent = function() {
		$(this).mouseenter(function() {
			$(this).parent().addClass('over');
		}).mouseleave(function() {
			$(this).parent().removeClass('over');
		});
	};
})(jQuery);

/*
 * Cycles through a set of elements having the same parent element.
 * params	direction 'prev' or 'next'
 * returns	jQuery object
 */
(function($){  
	$.fn.cycle = function(options) {
		var opts = $.extend({}, $.fn.cycle.defaults, options);
		if (opts.direction == 'next') {
			if ($(this).next().length > 0) return $(this).next(); else return $(this).siblings(':first');
		} else if (opts.direction == 'prev') {
			if ($(this).prev().length > 0) return $(this).prev(); else return $(this).siblings(':last');
		}
	};
})(jQuery);

/*
 * Generic single element view slideshow.
 */
(function($){  
	$.fn.singleElementViewSlideshow = function() {
		var itemContainer = this;
		var itemCounter = 0;
		$(itemContainer).children(".item").each(function() {
			$(this).attr("index", ++itemCounter);
		});
		$(itemContainer).parent().find(".nav .slideCounter .total").text(itemCounter);
		$(itemContainer).children(".item:not(:first)").fadeOut('normal');
		$(itemContainer).children(".item:first").addClass("active").fadeIn();
		if (itemCounter > 1) {
			$(itemContainer).parent().find(".nav").children().click(function(el) {
				el.preventDefault();
				$(itemContainer).children(".item.active").fadeOut().removeClass('active').cycle({direction: $(this).attr("class")}).addClass('active').fadeIn('normal', function() {
					$(itemContainer).parent().find(".nav .slideCounter .active").text($(itemContainer).children(".item.active").attr("index"));
				});
			});
		}
	};
})(jQuery);

/*
 * Homepage Generic single element view slideshow.
 */
(function($){  
	$.fn.singleElementViewSlideshowHome = function() {
		var itemContainer = this,
			itemCounter = 0,
			currInterval,
			stopped = false,
			$container = $(itemContainer),
			header = $container.siblings('.headertitle');

		
		header.append('<span class="slideCounter"><span class="active">1</span>/<span class="total"></span></span>');
		
		$container.children(".item").each(function() {
			$(this).attr("index", ++itemCounter);
		});
		
		if( $container.children('.item').length > 1 )
		{    
			var initInterval = function() {
				currInterval = setInterval( function(){
						$container.children(".item.active").fadeOut().removeClass('active').cycle({direction:"next"}).addClass('active').fadeIn('normal');
						$container.parent().find(".headertitle .slideCounter .active").text($(itemContainer).children(".item.active").attr("index"));
				},2500);
			}
			$container.bind('mouseover', function(e){
				clearInterval( currInterval );
			}).bind('mouseout',function(){
				if( !stopped )
					initInterval();
			});
		} else if ($container.children('.item').length == 1) {
			$(itemContainer).parent().find(".nav").hide();
			$(itemContainer).parent().find(".headertitle .slideCounter").hide();
		}
		
		$(itemContainer).parent().find(".headertitle .slideCounter .total").text(itemCounter);
		$(itemContainer).children(".item:not(:first)").fadeOut('normal');
		$(itemContainer).children(".item:first").addClass("active").fadeIn();
		if (itemCounter > 1) {
			$(itemContainer).parent().find(".nav").children().click(function(el) {
				el.preventDefault();
				clearInterval( currInterval );
				stopped = true;
				$(itemContainer).children(".item.active").fadeOut().removeClass('active').cycle({direction: $(this).attr("class")}).addClass('active').fadeIn('normal');//, function() {
				$(itemContainer).parent().find(".headertitle .slideCounter .active").text($(itemContainer).children(".item.active").attr("index"));
				//});
			});
		}
		

		
	};
})(jQuery);

/*
 * Image preloader
 */
$.preloadImages = function() {
	var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
	for(var i = a.length -1; i > 0; i--) {
		$("<img>").attr("src", a[i]);
	}
};

/*
 * CML Tabs
 * Converts DIV > H3, DIV > DL > DT DD layout to Tab appropriate HTML structure and enables Tab interactivity
 * Applied on the outer DIV
 */
(function($){  
	$.fn.cmlTabs = function() {
		var vtabsAggregator = $('<div/>').addClass('vtabsContainer');
		var vtabsTabsContainer = $('<ul/>').addClass('vtabsTabsContainer');
		var vtabsContentContainer = $('<div/>').addClass('vtabsContentContainer');
		var vtabsContainer = $(this);
		var tabCounter = 1;
		var active = ' active ';
		vtabsContainer.find('dt').each(function() {
			if (tabCounter > 1) active = '';
			vtabsTabsContainer.append('<li class="tab' + active + '" index="' + (tabCounter++) + '"><span>' + $(this).html() + '</span></li>');
		});
		tabCounter = 1;
		var hide = '';
		vtabsContainer.find('dd').each(function() {
			if (tabCounter > 1) hide = ' hide ';
			vtabsContentContainer.append('<div class="tab-content' + hide + '" index="' + (tabCounter++) + '">' + $(this).html() + '</div>');
		});
		vtabsAggregator.append(vtabsContainer.children('.title'));
		vtabsAggregator.append(vtabsTabsContainer);
		vtabsAggregator.append(vtabsContentContainer);
		vtabsAggregator.append('<div class="clear"> </div>');
		vtabsContainer.html(vtabsAggregator.html());
		vtabsContainer.children('ul.vtabsTabsContainer').children('.tab').click(function(el) {
			el.preventDefault();
			$(this).addClass('active').siblings().removeClass('active');
			$('div.vtabsContentContainer').children('.tab-content').addClass('hide');
			$('div.vtabsContentContainer').children('.tab-content[index|=' + $(this).attr('index') + ']').removeClass('hide');
			
			// jCarousel bug fix [START]
			var lastItem = $('.tab-content[index|=' + $(this).attr('index') + '] .carousel ul li:last');
			var itemNum = lastItem.attr("jcarouselindex");
			var totalItemWidth = (
				itemNum * (
					parseInt(lastItem.css("width")) +
					parseInt(lastItem.css("margin-left")) +
					parseInt(lastItem.css("margin-right")) +
					parseInt(lastItem.css("padding-left")) +
					parseInt(lastItem.css("padding-right"))
				)
			);
			$('.tab-content[index|=' + $(this).attr('index') + '] .carousel ul').css("width", totalItemWidth + "px");
			if ((totalItemWidth-20) < parseInt($(".carousel ul").parent().css("width"))) {
				$('.tab-content[index|=' + $(this).attr('index') + '] .carousel ul').parent().parent().find('.jcarousel-next-horizontal').addClass('jcarousel-next-disabled').addClass('jcarousel-next-disabled-horizontal');
			}
			// jCarousel bug fix [END]
		});
	};
})(jQuery);	

jQuery.fn.exists = function(){return jQuery(this).length>0;}

/*
 * Read/Write Cookies
 * Write: $.cookie('the_cookie', 'the_value');
 * Read: $.cookie('the_cookie');
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
