// remap jQuery to $
(function($){
	
	// manage custom select
	$.fn.extend({
		ySelect: function() {
			return this.each(function() {
				
				var elmt = $(this);
				var container = elmt.parent();
				
				var select = {
					params: {
						mainContent: '<div class="selectContainer"><div class="link"></div><div class="itemList"><ul></ul></div></div>'
					},
					getSelectedItem: function (obj) {
						var elmt = $(obj);
						var list = elmt.find('option').filter(':selected');
						return list;
					},
					show: function (obj) {
						var elmt = $(obj);
					},
					hide:function (obj) {
						var elmt = $(obj);
					},
					update: function (obj) {
						var elmt = $(obj);
						var container = elmt.parent();
						var link = $('.link', container);
						
						var selectedItem = select.getSelectedItem(elmt);
						link.html(selectedItem.text());
					},
					select: function (obj, value) {
						var elmt = $(obj);
						elmt.val(value);
						elmt.change();
						select.update(elmt);
					}
				};
		
				// create plugin html
				container.append(select.params.mainContent);
				
				var link = $('.link', container);
				var linkList = $('.itemList', container);
				
				// create item into link list
				$('option', elmt).each(function () {
					var optionItem = $(this);
					$('ul', linkList).append('<li><a href="#'+optionItem.attr('value')+'">'+optionItem.text()+'</a></li>');
					$('ul li:last a', linkList).click(function (e) {
						e.preventDefault();
						var item = $(this);
						var value = item.attr('href').split('#')[1];
						select.select(elmt, value);
						linkList.hide();
					});
				});
				
				// bind click on link
				link.click(function () {
					linkList.toggle();
				});
				
				// update first state
				select.update(elmt);
				
				// bind onChange event on select item
				elmt.change(function () {
					select.update(elmt);
				});
				
				// container on foreground when mouse hover
				container.parent().parent().hover(function () {
					var obj = $(this);
					obj.css('z-index', '2');
				}, function () {
					var obj = $(this);
					obj.css('z-index', '1');
					linkList.hide();
				});
				
			});
		}
	});
	
	/**
	 * @section		carousel
	 */
    $.fn.extend({// carousel plugin
        carousel: function(options) {
			
            var defaults = {				
				duration: 200,
				auto: false,
				waitToMove: 4000,
				pauseDuration: 30000,
				direction: 'h',
				nb : 1,
				effect: 'slide',
				moved: null,
				nav: null
            }
			
            var options =  $.extend(defaults, options);
			
            return this.each(function() {
                var o = options;
				
				var direction = o.direction;
				
				var obj = $(this);
				var ul = $('.wrapper > ul', obj);
				var lis = $('> li', ul);
				
				function lstItem() {
					return $('> :last', ul);
				}
				function fstItem() {
					return $('> :first', ul);
				}
				
				function init() {
					
					var firstItem = fstItem();
					
					for(var i = 0; i < lis.length; i++) {
						$(lis[i]).removeClass('carouselItem'+i).addClass('carouselItem'+i);
					}
					
					if(!firstItem.hasClass('first')) {
						firstItem.addClass('first')
					}
					
					if(direction == 'h') {
					
						var totalWidth = 0;
						lis.each(function () {
							totalWidth = totalWidth + itemTotalWidth(this);
						});
						
						ul.css({
							width: totalWidth+'px'
						});
						
					} else {
						
						var totalHeight = 0;
						lis.each(function () {
							totalHeight = totalHeight + itemTotalHeight(this);
						});
						
						ul.css({
							height: totalHeight+'px'
						});
						
					}
					
					// bind navigation
					var nextLink = $('.next', obj);
					var prevLink = $('.prev', obj);
					nextLink.click(function (e) {
						next();
						return false;
					});
					
					prevLink.click(function (e) {
						previous();
						return false;
					});
					
					if(o.auto) {
						play({init: true});
					}
					
					if(o.nav) {
						var nav = $(o.nav);
						$('a', nav).click(function () {
							var elmt = $(this);
							var target = elmt.parent().index();
							
							gotoIndex(target);
							
							return false;
						});
					}
				}
				
				function gotoIndex(target) {
					var current = fstItem().attr('class').split('arouselItem')[1].split(' ')[0];
					
					var find = false;
					if(target != current) {
						var i = 1;
						while(!find) {
							if($('> li:eq('+i+')', ul).hasClass('carouselItem'+target)) {
								find = true;
							} else {
								i++;
							}
						}
						
						next(i);
					}
					if(o.auto) {
						pause();
					}
				}
				
				obj.bind('play', function () {
					play({init: true});
				});
				function play (p) {
					if(!p) {
						next();
					} else if (!p.init) {
						next();
					}
					var cicleDuration = o.waitToMove + o.duration;
					function moveCarousel() {
						next();
					}
					cicle = setInterval(moveCarousel, cicleDuration);
				}
				
				obj.bind('stop', function () {
					stop();
				});
				var stop = function() {
					if(typeof(cicle) != 'undefined') {
						window.clearInterval(cicle);
					}
					if(typeof(pauseCicle) != 'undefined') {
						window.clearTimeout(pauseCicle);
					}
				}
				
				function pause() {
					function restart() {
						play();
					}
					stop();
					pauseCicle = window.setTimeout(restart, o.pauseDuration);
				}
				
				function itemTotalWidth(obj) {
					var itemWidth 		= parseInt(String($(obj).width()).replace('px', '').replace(' ', ''));
					
					if($(obj).css('margin-left') != 'auto') {
						var leftMargin 		= parseInt(String($(obj).css('margin-left')).replace('px', '').replace(' ', ''));
					} else {
						var leftMargin = 0;
					}
					
					if($(obj).css('margin-right') != 'auto') {
						var rightMargin 	= parseInt(String($(obj).css('margin-right')).replace('px', '').replace(' ', ''));
					} else {
						var rightMargin = 0;
					}
					
					if($(obj).css('padding-left') != 'auto') {
						var leftPadding 	= parseInt(String($(obj).css('padding-left')).replace('px', '').replace(' ', ''));
					} else {
						var leftPadding = 0;
					}
					
					if($(obj).css('padding-right') != 'auto') {
						var rightPadding	= parseInt(String($(obj).css('padding-right')).replace('px', '').replace(' ', ''));
					} else {
						var rightPadding = 0;
					}
					var totalWidth = itemWidth + leftMargin + rightMargin + leftPadding + rightPadding;
					return totalWidth;
				}
				
				function itemTotalHeight(obj) {
					var itemHeight 		= parseInt(String($(obj).height()).replace('px', '').replace(' ', ''));
					
					if($(obj).css('margin-top') != 'auto') {
						var topMargin 		= parseInt(String($(obj).css('margin-top')).replace('px', '').replace(' ', ''));
					} else {
						var topMargin = 0;
					}
					
					if($(obj).css('margin-bottom') != 'auto') {
						var bottomMargin 	= parseInt(String($(obj).css('margin-bottom')).replace('px', '').replace(' ', ''));
					} else {
						var bottomMargin = 0;
					}
					
					if($(obj).css('padding-top') != 'auto') {
						var topPadding 		= parseInt(String($(obj).css('padding-top')).replace('px', '').replace(' ', ''));
					} else {
						var topPadding = 0;
					}
					
					if($(obj).css('padding-bottom') != 'auto') {
						var bottomPadding	= parseInt(String($(obj).css('padding-bottom')).replace('px', '').replace(' ', ''));
					} else {
						var bottomPadding = 0;
					}
					var totalHeight = itemHeight + topMargin + bottomMargin + topPadding + bottomPadding;
					return totalHeight;
				}
				
				function previous(i) {
					if(o.direction == 'h') {
						previousH(i);
					} else {
						previousV(i);
					}
				}
				
				function previousH(i) {
					if(!obj.hasClass('move')) {
						
						var distance = 0;
						var nb = o.nb;
						if(i > 0) {
							nb = i;
						}
						var lastItems = new Array();
						var nbLis = lis.length;
						
						for(var i = 0; i < nb; i++) {
							lastItems[i] = $('> :last', ul);
							distance = distance + itemTotalWidth(lastItems[i]);
							$('> :last', ul).remove();
							ul.prepend(lastItems[i]);
						}
						
						ul.css({'left':0});
						
						$('> .first', ul).removeClass('first');
						$('> :first', ul).addClass('first');
						
						ul.css({'left': '-'+distance+'px'}).animate({
							'left': '0px'
						}, o.duration, function () {
							obj.removeClass('move');
							obj.trigger('moved');
							if ($.isFunction(o.moved)) {
								o.moved(obj);
							}
						});
						
					}
				}
				
				function previousV(i) {
					if(!obj.hasClass('move')) {
						obj.addClass('move');
						
						var distance = 0;
						var nb = o.nb;
						if(i > 0) {
							nb = i;
						}
						var lastItems = new Array();
						var nbLis = lis.length;
						
						for(var i = 0; i < nb; i++) {
							lastItems[i] = $('> :last', ul);
							distance = distance + itemTotalHeight(lastItems[i]);
							$('> :last', ul).remove();
							ul.prepend(lastItems[i]);
						}
						
						ul.css({'top':0});
						
						$('> .first', ul).removeClass('first');
						$('> :first', ul).addClass('first');
						
						ul.css({'top': '-'+distance+'px'}).animate({
							'top': '0px'
						}, o.duration, function () {
							obj.removeClass('move');
							obj.trigger('moved');
							if ($.isFunction(o.moved)) {
								o.moved(obj);
							}
						});
						
					}
				}
				
				function next(i) {
					if(o.direction == 'h') {
						nextH(i);
					} else {
						nextV(i);
					}
				}
				
				function nextH(i) {
					if(!obj.hasClass('move')) {
						obj.addClass('move');
						
						var distance = 0;
						var nb = o.nb;
						if(i > 0) {
							nb = i;
						}
						for(var i = 0; i < nb; i++) {
							distance = distance + itemTotalWidth($('> li:eq('+i+')', ul));
						}
						
						ul.animate({
							'left': '-'+distance+'px'
						}, o.duration, function () {
							
							for(var i = 0; i < nb; i++) {
								var firstItem = $('> :first', ul);
								$('> .first', ul).remove();
								
								ul.css({'left':0}).append(firstItem);
								
								$('> .first', ul).removeClass('first');
								$('> :first', ul).addClass('first');
							}
							
							obj.removeClass('move');
							obj.trigger('moved');
							if ($.isFunction(o.moved)) {
								o.moved(obj);
							}
						});
					}
				}
				
				function nextV(i) {
					if(!obj.hasClass('move')) {
						obj.addClass('move');
						
						var distance = 0;
						var nb = o.nb;
						if(i > 0) {
							nb = i;
						}
						for(var i = 0; i < nb; i++) {
							distance = distance + itemTotalHeight($('> li:eq('+i+')', ul));
						}
						
						ul.animate({
							'top': '-'+distance+'px'
						}, o.duration, function () {
							
							for(var i = 0; i < nb; i++) {
								var firstItem = $('> :first', ul);
								$('> .first', ul).remove();
								
								ul.css({'top':0}).append(firstItem);
								
								$('> .first', ul).removeClass('first');
								$('> :first', ul).addClass('first');
							}
							
							obj.removeClass('move');
							obj.trigger('moved');
							if ($.isFunction(o.moved)) {
								o.moved(obj);
							}
						});
						
					}
				}
				
				init();
            });
        }
    });// END carousel

	/**
	 * @section			auto empty form fields
	 */
	autoEmptyFields = function (elmt, val) {
		var elmt = $(elmt);
		elmt.focus(function () {
			var elmt = $(this);
			if(elmt.val() == val) {
				elmt.val('');
			}
		});
		elmt.blur(function () {
			var elmt = $(this);
			if(elmt.val() == '') {
				elmt.val(val);
			}
		});
	};

	/**
	 * @section		set global for document & window
	 */
	w = window;
	W = jQuery(w);
	d = document;
	D = jQuery(d);
	B = jQuery('body');

	/**
	 * @section		create global var isIE
	 */
	isIE = false;
	var manageIsIE = {
		init: function () {
			if (jQuery.browser.msie) {
				isIE = true;
				if(parseInt(jQuery.browser.version) == 6) {
					isIE = 6;
				} else if (parseInt(jQuery.browser.version) == 7) {
					isIE = 7;
				} else if (parseInt(jQuery.browser.version) == 8) {
					isIE = 8;
				} else if (parseInt(jQuery.browser.version) == 9) {
					isIE = 9;
				} else if (parseInt(jQuery.browser.version) == 10) {
					isIE = 10;
				} else if (parseInt(jQuery.browser.version) == 11) {
					isIE = 11;
				}
			}
		}
	};
	manageIsIE.init();
	
})(window.jQuery);

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};

// catch all document.write() calls
(function(doc){
	var write = doc.write;
	doc.write = function(q){
		log('document.write(): ',arguments);
		if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);
	};
})(document);
