// page init
jQuery(function(){
	initLightbox();
	initGallery();
	initPopups();
	initCustomForms();
	initValidation();
	initOpenClose();
	fixTrans();
        
                        
                        
                        $('.modal').appendTo('body');
                        //ie7Fix();
                        initMainNav();
                        
                        if($('#media-releases-home'))
                        {
                            $('#corp-news').append($('#media-releases-home').html());
                        }
                        
                        if ($('#stock-ticker'))
                        {
                            $('#ticker').append($('#stock-ticker').html());
                        }
                        adjustRightBarHeight();
                        
       
        var currentUrl = window.location.href;
        currentUrl = currentUrl.slice(isContained(currentUrl, "/en-US"));
        currentUrl = currentUrl.toLowerCase();
           if (currentUrl == "/en-us/pages/default.aspx" || currentUrl == "/en-us/pages/default.aspx#")
           {
                initTimer();
           }

}); 


// init gallery
function initGallery(){
	jQuery('#content div.gallery-holder').slideshow();
	jQuery('div.column').galleryCircle();
	jQuery('div.gallery-box').galleryScroll();
        jQuery('div.library-gallery-box').galleryScroll({
            holderList: 'library-gallery-holder'
        });
        jQuery('div.switcher').galleryScroll({
                holderList: 'div.switcher-holder',
                circleSlide: true
            });
            
        $('.modal').each(function(){
            
            
            jQuery('#' + $(this).find('.video-gallery').attr('id')).slideshow({
                    slides:'#' + $(this).find('.video').attr('id') + ' > li',
                    nextBtn: '#' + $(this).find('.btn-next').attr('id'),
                    prevBtn: '#' + $(this).find('.btn-prev').attr('id'),
                    pagingHolder:'#' + $(this).find('.switcher-holder').attr('id'),
                    pagingTag:'li',
                    createPaging:true,
                    effect:'slideX'
            });
        });
        
        jQuery('div.press-gallery').slideshow({
		slides:'ul.press > li',
		nextBtn:'a.btn-next',
		prevBtn:'a.btn-prev',
		pagingHolder:'div.switcher-holder',
		pagingTag:'li',
		createPaging:false,
		effect:'fade',
                autoHeight: true
	});
        
        var currentUrl = window.location.href;
        currentUrl = currentUrl.slice(isContained(currentUrl, "/en-US"));
        currentUrl = currentUrl.toLowerCase();
        
        if (currentUrl == "/en-us/pages/default.aspx" || currentUrl == "/en-us/pages/default.aspx#")
        {
            jQuery('div.middle-column-slider').cycle({
                    fx: 'fade',
                    speed: 650,
                    next: 'a.next',
                    prev: 'a.prev',
                    timeout: 0
            });
        }
};

// lightbox init
function initLightbox(){
	jQuery('a.with-popup').each(function(){
		jQuery(this).modalPopup();
	});
	jQuery('a.gallery-popup').each(function(i){
		jQuery(this).modalPopup({
			beforeOpen:function(){
				var index = i;
				jQuery('div.carousel').fadeGallery({
					startSlide:index
				})
			}
		})
	})
        
        //init image library popup carousels
        jQuery('.library-popup').each(function(){
            //alert('#' + $(this).find('.carousel').attr('id'));
            jQuery('#' + $(this).find('.carousel').attr('id')).fadeGallery({
                slideElements: '#' + $(this).find('.modal-slider').attr('id') + ' > div.modal-slide',
                pagerHolder: '#' + $(this).find('.gallery-box').attr('id'),
                pagerLinks: '#' + $(this).find('.gallery').attr('id') + ' li',
                activeClass: 'active',
                startSlide: 0
                
            })
        });
        
        
};

// popups init
function initPopups(){
	var activeClass = 'active-popup';
	var holders = jQuery('div.popup-holder');
	var popups = jQuery('div.popup');
	holders.each(function(){
		var hold = jQuery(this);
		var rel = hold.find('.ph-content>a').attr('rel');
		var popup = jQuery('#'+rel);
		var close = jQuery('a.close, a.up, a.down');
		hold.click(function(){
			holders.removeClass(activeClass);
			popups.hide();
			if(!hold.hasClass(activeClass)){
				hold.addClass(activeClass);
				popup.show();
			}
		});
		close.click(function(){
			hold.removeClass(activeClass);
			popup.hide();
		})
	})
};

// init open close
function initOpenClose(){
	var activeClass = 'active';
	var holders = jQuery('div.world-map > div.open-close');
	holders.each(function(){
		var hold = jQuery(this);
		var popup = hold.find('div.continent-popup');
		var opener = hold.find('a.continent, a.close');
		var items = popup.find('ul.countries a');
		var parentBox = hold.find('div.parent-box');
		items.each(function(){
			var item = jQuery(this);
			var back = item.find('a.back');
			var box = jQuery('#'+item.attr('rel'));
			var back = box.find('a.back');
			item.click(function(){
				parentBox.hide();
				box.show();
				return false;
			});
			back.click(function(){
				parentBox.show();
				box.hide();
				return false;
			})
		});
		opener.click(function(){
			if(!hold.hasClass(activeClass)){
				holders.removeClass(activeClass);
				hold.addClass(activeClass);
			}  else {
				hold.removeClass(activeClass);
			}
			return false;
		});
		jQuery(document).click(function(event) {
			if (jQuery(event.target).closest('div.continent-popup').length) return;
			holders.removeClass(activeClass);
			event.stopPropagation();
		});
	});
};

// init validation
function initValidation(){
	var _errorClass = 'error';
	var _disabledClass = 'disabled-continue';
	var _regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	$('form.validate').each(function(){
		var _form = $(this);
		var _btn = _form.find('a.continue');
		var _items = _form.find('input, textarea, select');
		function checkFields() {
			var _flag = false;
			_form.find('.'+_errorClass).removeClass(_errorClass);

			// fields validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test($(this).val())) addError($(this));
			});
			_form.find('input.required').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
			});
			_form.find('textarea.required').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
			});
			_form.find('select.required-select').each(function(){
				if(!this.selectedIndex) addError($(this));
			});

			// error class adding
			function addError(_obj) {
				_obj.addClass(_errorClass);
				_flag=true;
			}
			return _flag;
		};
		_items.bind('keyup blur click change',function(){
			check();
			
		});
		check();
		function check(){
			if(checkFields()) {
				_btn.addClass(_disabledClass);
			} else {
				_btn.removeClass(_disabledClass);
			}
		};
		// submit form
		_btn.click(function(){
			_form.submit();
			return false;
		});
		
		// catch form submit event
		_form.submit(function(){
			if(checkFields()) {
				return false;
			}
		});
	});
}

// IE6 png fix
var transparentImage = "/SiteCollectionImages/none.gif";
function fixTrans(){
	if (typeof document.body.style.maxHeight == 'undefined') {

	var imgs = document.getElementsByTagName("img");
	
	for (i = 0; i < imgs.length; i++)
	{	
		if (imgs[i].src.indexOf(transparentImage) != -1)
		{
			return;
		}

		if (imgs[i].src.indexOf(".png") != -1)
			{
				var src = imgs[i].src;
				imgs[i].src = transparentImage;
				imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
				imgs[i].style.display = "block";
			}
		}	
	}
}

// cutom form init
function initCustomForms(){
	jQuery('select').customSelect();
	jQuery('input:radio').customRadio();
};

// custom forms plugin
(function(jQuery){
	// custom radios module
	jQuery.fn.customRadio = function(_options){
		var _options = jQuery.extend({
			radioStructure: '<div></div>',
			radioDisabled: 'disabled',
			radioDefault: 'radioArea',
			radioChecked: 'radioAreaChecked'
		}, _options);
		return this.each(function(){
			var radio = jQuery(this);
			if(!radio.hasClass('outtaHere') && radio.is(':radio')){
				var replaced = jQuery(_options.radioStructure);
				this._replaced = replaced;
				if(radio.is(':disabled')) replaced.addClass(_options.radioDisabled);
				else if(radio.is(':checked')) replaced.addClass(_options.radioChecked);
				else replaced.addClass(_options.radioDefault);
				replaced.click(function(){
					if(jQuery(this).hasClass(_options.radioDefault)){
						radio.attr('checked', 'checked');
						changeRadio(radio.get(0));
					}
				});
				radio.click(function(){
					changeRadio(this);
				});
				replaced.insertBefore(radio);
				radio.addClass('outtaHere');
			}
		});
		function changeRadio(_this){
			jQuery(_this).change();
			jQuery('input:radio[name='+jQuery(_this).attr("name")+']').not(_this).each(function(){
				if(this._replaced && !jQuery(this).is(':disabled')) this._replaced.removeClass().addClass(_options.radioDefault);
			});
			_this._replaced.removeClass().addClass(_options.radioChecked);
		}
	}

	// custom selects module
	jQuery.fn.customSelect = function(_options) {
		var _options = jQuery.extend({
			selectStructure: '<div class="selectArea"><span class="left"></span><span class="center"></span><a href="#" class="selectButton"></a><div class="disabled"></div></div>',
			hideOnMouseOut: false,
			copyClass: true,
			selectText: '.center',
			selectBtn: '.selectButton',
			selectDisabled: '.disabled',
			optStructure: '<div class="optionsDivVisible"><div class="select-top"></div><div class="select-center"><ul></ul><div class="select-bottom"></div></div>',
			optList: 'ul'
		}, _options);
		return this.each(function() {
			var select = jQuery(this);
			if(!select.hasClass('outtaHere')) {
				if(select.is(':visible')) {
					var hideOnMouseOut = _options.hideOnMouseOut;
					var copyClass = _options.copyClass;
					var replaced = jQuery(_options.selectStructure);
					var selectText = replaced.find(_options.selectText);
					var selectBtn = replaced.find(_options.selectBtn);
					var selectDisabled = replaced.find(_options.selectDisabled).hide();
					var optHolder = jQuery(_options.optStructure);
					var optList = optHolder.find(_options.optList);
					if(copyClass) optHolder.addClass('drop-'+select.attr('class'));

					if(select.attr('disabled')) selectDisabled.show();
					select.find('option').each(function(){
						var selOpt = jQuery(this);
						var _opt = jQuery('<li><a href="#">' + selOpt.html() + '</a></li>');
						if(selOpt.attr('selected')) {
							selectText.html(selOpt.html());
							_opt.addClass('selected');
						}
						_opt.children('a').click(function() {
							optList.find('li').removeClass('selected');
							select.find('option').removeAttr('selected');
							jQuery(this).parent().addClass('selected');
							selOpt.attr('selected', 'selected');
							selectText.html(selOpt.html());
							select.change();
							optHolder.hide();
							return false;
						});
						optList.append(_opt);
					});
					replaced.width(select.outerWidth());
					replaced.insertBefore(select);
					optHolder.css({
						width: select.outerWidth(),
						display: 'none',
						position: 'absolute'
					});
					jQuery(document.body).append(optHolder);

					var optTimer;
					replaced.hover(function() {
						if(optTimer) clearTimeout(optTimer);
					}, function() {
						if(hideOnMouseOut) {
							optTimer = setTimeout(function() {
								optHolder.hide();
							}, 200);
						}
					});
					optHolder.hover(function(){
						if(optTimer) clearTimeout(optTimer);
					}, function() {
						if(hideOnMouseOut) {
							optTimer = setTimeout(function() {
								optHolder.hide();
							}, 200);
						}
					});
					selectBtn.click(function() {
						if(optHolder.is(':visible')) {
							optHolder.hide();
						}
						else{
							if(_activeDrop) _activeDrop.hide();
							optHolder.children('ul').css({height:'auto', overflow:'hidden'});
							optHolder.css({
								top: replaced.offset().top + replaced.outerHeight(),
								left: replaced.offset().left,
								display: 'block'
							});
							if(optHolder.children('ul').height() > 200) optHolder.children('ul').css({height:200, overflow:'auto'});
							_activeDrop = optHolder;
						}
						return false;
					});
					select.addClass('outtaHere');
				}
			}
		});
	}

	// event handler on DOM ready
	var _activeDrop;
	jQuery(function(){
		jQuery('body').click(hideOptionsClick)
		jQuery(window).resize(hideOptions)
	});
	function hideOptions() {
		if(_activeDrop && _activeDrop.length) {
			_activeDrop.hide();
			_activeDrop = null;
		}
	}
	function hideOptionsClick(e) {
		if(_activeDrop && _activeDrop.length) {
			var f = false;
			jQuery(e.target).parents().each(function(){
				if(this == _activeDrop) f=true;
			});
			if(!f) {
				_activeDrop.hide();
				_activeDrop = null;
			}
		}
	}
})(jQuery);

// IE6 hover plugin
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 u=k(){9 g=/^([^#.>`]*)(#|\\.|\\>|\\`)(.+)$/;k u(a,b){9 c=a.J(/\\s*\\,\\s*/);9 d=[];n(9 i=0;i<c.l;i++){d=d.v(o(c[i],b))};6 d};k o(a,b,c){a=a.z(" ","`");9 d=a.r(g);9 e,5,m,7,i,h;9 f=[];4(d==8){d=[a,a]};4(d[1]==""){d[1]="*"};4(c==8){c="`"};4(b==8){b=E};K(d[2]){w"#":7=d[3].r(g);4(7==8){7=[8,d[3]]};e=E.L(7[1]);4(e==8||(d[1]!="*"&&!x(e,d[1]))){6 f};4(7.l==2){f.A(e);6 f};6 o(7[3],e,7[2]);w".":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};7=d[3].r(g);4(7!=8){4(e.j==8||e.j.r("(\\\\s|^)"+7[1]+"(\\\\s|$)")==8){q};m=o(7[3],e,7[2]);f=f.v(m)}y 4(e.j!=8&&e.j.r("(\\\\s|^)"+d[3]+"(\\\\s|$)")!=8){f.A(e)}};6 f;w">":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};m=o(d[3],e,">");f=f.v(m)};6 f;w"`":5=p(b,d[1]);n(i=0,h=5.l;i<h;i++){e=5[i];m=o(d[3],e,"`");f=f.v(m)};6 f;M:4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};f.A(e)};6 f}};k p(a,b){4(b=="*"&&a.F!=8){6 a.F};6 a.p(b)};k x(a,b){4(b=="*"){6 N};6 a.O.G().z("P:","")==b.G()};6 u}();k Q(a,b){9 c=u(a);n(9 i=0;i<c.l;i++){c[i].R=k(){4(t.j.H(b)==-1){t.j+=" "+b}};c[i].S=k(){4(t.j.H(b)!=-1){t.j=t.j.z(b,"")}}}}4(D.I&&!D.T){D.I("U",V)}',58,58,'||||if|listNodes|return|subselector|null|var||||||||limit||className|function|length|listSubNodes|for|doParse|getElementsByTagName|continue|match||this|parseSelector|concat|case|matchNodeNames|else|replace|push|childNodes|nodeType|window|document|all|toLowerCase|indexOf|attachEvent|split|switch|getElementById|default|true|nodeName|html|hoverForIE6|onmouseover|onmouseout|opera|onload|ieHover'.split('|'),0,{}))
function ieHover() {
	hoverForIE6('#nav li.whith-drop , .button-bottom, .gallery-link, .popup-holder','ie-hover');
};


// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'div.modal-slider > div.modal-slide',
		pagerGener: false,
		pagerHold: 'div.switcher',
		pagerLinks:'ul.gallery li',
		btnNext:'a.next2',
		btnPrev:'a.prev2',
		btnPlayPause:'a.play-pause',
		btnPlay:'a.play',
		btnPause:'a.pause',
		pausedClass:'paused',
		disabledClass: 'disabled',
		playClass:'playing',
		activeClass:'active',
		currentNum:'em.cur',
		allNum:'em.all',
		startSlide:null,
		noCircle:false,
		caption:'ul.caption > li',
		pauseOnHover:true,
		autoRotation:false,
		autoHeight:true,
		onChange:false,
		switchTime:3000,
		duration:650,
		event:'click'
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _slides = jQuery(_options.slideElements, _this);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
		var _btnPause = jQuery(_options.btnPause, _this);
		var _btnPlay = jQuery(_options.btnPlay, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _pausedClass = _options.pausedClass;
		var _playClass = _options.playClass;
		var _autoHeight = _options.autoHeight;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
		var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
		var _startSlide = _options.startSlide;
		var _noCycle = _options.noCircle;
		var _onChange = _options.onChange;
		var _pagerGener = _options.pagerGener;
		var _pagerHold = jQuery(_options.pagerHold,_this);
		var _caption = jQuery(_options.caption,_this);
		var _paging = '';
		if(_pagerGener){
			for(var i=0; i< _slides.length; i++){
				_paging += '<li><a href="#">'+(i+1)+'</a></li>';
			}
			_pagerHold.html('<ul>'+_paging+'</ul>');
		}
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		// gallery init
		var _hover = false;
		var _prevIndex = 0;
		var _currentIndex = 0;
		var _slideCount = _slides.length;
		var _timer;
		if(_slideCount < 2) return;
		_slides.eq(_currentIndex).parent().css({height:_slides.eq(_currentIndex).outerHeight(true)});
		_prevIndex = _slides.index(_slides.filter('.'+_activeClass));
		if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
		else _currentIndex = _prevIndex;
		if(_startSlide != null) {
			if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
			else _prevIndex = _currentIndex = parseInt(_startSlide);
		}
		_slides.hide().eq(_currentIndex).show();
		_caption.hide().eq(_currentIndex).show();
		if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
		else _this.removeClass(_playClass).addClass(_pausedClass);
                if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
		
		// gallery control
		if(_btnPrev.length) {
			_btnPrev.unbind(_controlEvent+'.fade');
			_btnPrev.bind(_controlEvent+'.fade',function(){
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.unbind(_controlEvent+'.fade');
			_btnNext.bind(_controlEvent+'.fade',function(){
				nextSlide();
				return false;
			});
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).unbind(_controlEvent+'.fade');
				jQuery(this).bind(_controlEvent+'.fade',function(){
					if(_currentIndex != _ind) {
						_prevIndex = _currentIndex;
						_currentIndex = _ind;
						jQuery('.info-box').hide();
						jQuery('.open-info').removeClass('opened-info');
						switchSlide();
					}
					return false;
				});
			});
		}

		// play pause section
		if(_btnPlayPause.length) {
			_btnPlayPause.bind(_controlEvent,function(){
				if(_this.hasClass(_pausedClass)) {
					_this.removeClass(_pausedClass).addClass(_playClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_autoRotation = false;
					if(_timer) clearTimeout(_timer);
					_this.removeClass(_playClass).addClass(_pausedClass);
				}
				return false;
			});
		}
		if(_btnPlay.length) {
			_btnPlay.bind(_controlEvent,function(){
				_this.removeClass(_pausedClass).addClass(_playClass);
				_autoRotation = true;
				autoSlide();
				return false;
			});
		}
		if(_btnPause.length) {
			_btnPause.bind(_controlEvent,function(){
				_autoRotation = false;
				if(_timer) clearTimeout(_timer);
				_this.removeClass(_playClass).addClass(_pausedClass);
				return false;
			});
		}

		// gallery animation
		function prevSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex > 0) _currentIndex--;
			else {
				if(_noCycle) return;
				else _currentIndex = _slideCount-1;
			}
			switchSlide();
		}
		function nextSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex < _slideCount-1) _currentIndex++;
			else {
				if(_noCycle) return;
				else _currentIndex = 0;
			}
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
			if(_currentNum) _currentNum.text(_currentIndex+1);
			if(_allNum) _allNum.text(_slideCount);
			_slides.eq(_prevIndex).removeClass(_activeClass);
			_slides.eq(_currentIndex).addClass(_activeClass);
			if(_noCycle) {
				if(_btnPrev.length) {
					if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
					else _btnPrev.removeClass(_disabledClass);
				}
				if(_btnNext.length) {
					if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
					else _btnNext.removeClass(_disabledClass);
				}
			}
			if(typeof _onChange === 'function') {
				_onChange(_this, _currentIndex);
			}
		}
		function switchSlide() {
			_slides.eq(_prevIndex).fadeOut(_duration);
			_slides.eq(_currentIndex).fadeIn(_duration);
			_caption.eq(_prevIndex).fadeOut();
			_caption.eq(_currentIndex).fadeIn();
			if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		refreshStatus();
		autoSlide();
	});
};

/*
 * jQuery galleryScroll v1.5.2
 */

/*
	************* OPTIONS ************************************** default ****************
	btPrev         - link for previos [selector]    	btPrev: 'a.btn-pre'
	btNext         - link for next [selector]		btNext: 'a.btn-next'
	holderList     - image list holder [Tag name]		holderList: 'div'
	scrollElParent - list [Tag name]			scrollElParent: 'ul'
	scrollEl       - list element [Tag name]		scrollEl: 'li'
	slideNum       - view slide numbers [boolean]		slideNum: false
	duration       - duration slide [1000 - 1sec]		duration : 1000
	step           - slide step [int]			step: false
	circleSlide    - slide circle [boolean]			circleSlide: true
	disableClass   - class for disable link	[string] 	disableClass: 'disable'
	funcOnclick    - callback function			funcOnclick: null
	innerMargin    - inner margin, use width step [px]      innerMargin:0
	autoSlide      - auto slide [1000 - 1sec]               autoSlide:false
	*************************************************************************************
*/
jQuery.fn.galleryScroll = function(_options){
	// defaults options	
	var _options = jQuery.extend({
		btPrev: 'a.prev',
		btNext: 'a.next',
		holderList: 'div.gallery-holder',
		scrollElParent: 'ul',
		scrollEl: 'li',
		slideNum: false,
		duration : 650,
		step: 1,
		circleSlide: false,
		disableClass: 'disable',
		funcOnclick: null,
		autoSlide:false,
		innerMargin:0,
		stepWidth:false
	},_options);

	return this.each(function(){
		var _this = jQuery(this);

		var _holderBlock = jQuery(_options.holderList,_this);
		var _gWidth = _holderBlock.width();
		var _animatedBlock = jQuery(_options.scrollElParent,_holderBlock);
		var _liWidth = jQuery(_options.scrollEl,_animatedBlock).outerWidth(true);
		var _liSum = jQuery(_options.scrollEl,_animatedBlock).length * _liWidth;
		var _margin = -_options.innerMargin;
		var f = 0;
		var _step = 0;
		var _autoSlide = _options.autoSlide;
		var _timerSlide = null;
		if (!_options.step) _step = _gWidth; else _step = _options.step*_liWidth;
		if (_options.stepWidth) _step = _options.stepWidth;
		
		if (!_options.circleSlide) {
			if (_options.innerMargin == _margin)
				jQuery(_options.btPrev,_this).addClass('prev-'+_options.disableClass);
		}
		if (_options.slideNum && !_options.step) {
			var _lastSection = 0;
			var _sectionWidth = 0;
			while(_sectionWidth < _liSum)
			{
				_sectionWidth = _sectionWidth + _gWidth;
				if(_sectionWidth > _liSum) {
				       _lastSection = _sectionWidth - _liSum;
				}
			}
		}
		if (_autoSlide) {
				_timerSlide = setTimeout(function(){
					autoSlide(_autoSlide);
				}, _autoSlide);
			_animatedBlock.hover(function(){
				clearTimeout(_timerSlide);
			}, function(){
				_timerSlide = setTimeout(function(){
					autoSlide(_autoSlide)
				}, _autoSlide);
			});
		}
	
		// click button 'Next'
		jQuery(_options.btNext,_this).bind('click',function(){
			jQuery(_options.btPrev,_this).removeClass('prev-'+_options.disableClass);
			if (!_options.circleSlide) {
				if (_margin + _step  > _liSum - _gWidth - _options.innerMargin) {
					if (_margin != _liSum - _gWidth - _options.innerMargin) {
						_margin = _liSum - _gWidth  + _options.innerMargin;
						jQuery(_options.btNext,_this).addClass('next-'+_options.disableClass);
						_f2 = 0;
					} 
				} else {
					_margin = _margin + _step;
					if (_margin == _liSum - _gWidth - _options.innerMargin) {
						jQuery(_options.btNext,_this).addClass('next-'+_options.disableClass);_f2 = 0;
					} 					
				}
			} else {
				if (_margin + _step  > _liSum - _gWidth + _options.innerMargin) {
					if (_margin != _liSum - _gWidth + _options.innerMargin) {
						_margin = _liSum - _gWidth  + _options.innerMargin;
					} else {
						_f2 = 1;
						_margin = -_options.innerMargin;
					}
				} else {
					_margin = _margin + _step;
					_f2 = 0;
				}
			} 
			
			_animatedBlock.animate({marginLeft: -_margin+"px"}, {queue:false,duration: _options.duration });
			
			if (_timerSlide) {
				clearTimeout(_timerSlide);
				_timerSlide = setTimeout(function(){
					autoSlide(_options.autoSlide)
				}, _options.autoSlide);
			}
			
			if (_options.slideNum && !_options.step) jQuery.fn.galleryScroll.numListActive(_margin,jQuery(_options.slideNum, _this),_gWidth,_lastSection);		
			if (jQuery.isFunction(_options.funcOnclick)) {
				_options.funcOnclick.apply(_this);
			}
			return false;
		});
		// click button 'Prev'
		var _f2 = 1;
		jQuery(_options.btPrev, _this).bind('click',function(){
			jQuery(_options.btNext,_this).removeClass('next-'+_options.disableClass);
			if (_margin - _step >= -_step - _options.innerMargin && _margin - _step <= -_options.innerMargin) {
				if (_f2 != 1) {
					_margin = -_options.innerMargin;
					_f2 = 1;
				} else {
					if (_options.circleSlide) {
						_margin = _liSum - _gWidth  + _options.innerMargin;
						f=1;_f2=0;
					} else {
						_margin = -_options.innerMargin
					}
				}
			} else if (_margin - _step < -_step + _options.innerMargin) {
				_margin = _margin - _step;
				f=0;
			}
			else {_margin = _margin - _step;f=0;};
			
			if (!_options.circleSlide && _margin == _options.innerMargin) {
				jQuery(this).addClass('prev-'+_options.disableClass);
				_f2=0;
			}
			
			if (!_options.circleSlide && _margin == -_options.innerMargin) jQuery(this).addClass('prev-'+_options.disableClass);
			_animatedBlock.animate({marginLeft: -_margin + "px"}, {queue:false, duration: _options.duration});
			
			if (_options.slideNum && !_options.step) jQuery.fn.galleryScroll.numListActive(_margin,jQuery(_options.slideNum, _this),_gWidth,_lastSection);
			
			if (_timerSlide) {
				clearTimeout(_timerSlide);
				_timerSlide = setTimeout(function(){
					autoSlide(_options.autoSlide)
				}, _options.autoSlide);
			}
			
			if (jQuery.isFunction(_options.funcOnclick)) {
				_options.funcOnclick.apply(_this);
			}
			return false;
		});
		
		if (_liSum <= _gWidth) {
			jQuery(_options.btPrev,_this).addClass('prev-'+_options.disableClass).unbind('click');
			jQuery(_options.btNext,_this).addClass('next-'+_options.disableClass).unbind('click');
		}
		// auto slide
		function autoSlide(autoSlideDuration){
			//if (_options.circleSlide) {
				jQuery(_options.btNext,_this).trigger('click');
			//}
		};
		// Number list
		jQuery.fn.galleryScroll.numListCreate = function(_elNumList, _liSumWidth, _width, _section){
			var _numListElC = '';
			var _num = 1;
			var _difference = _liSumWidth + _section;
			while(_difference > 0)
			{
				_numListElC += '<li><a href="">'+_num+'</a></li>';
				_num++;
				_difference = _difference - _width;
			}
			jQuery(_elNumList).html('<ul>'+_numListElC+'</ul>');
		};
		jQuery.fn.galleryScroll.numListActive = function(_marginEl, _slideNum, _width, _section){
			if (_slideNum) {
				jQuery('a',_slideNum).removeClass('active');
				var _activeRange = _width - _section-1;
				var _n = 0;
				if (_marginEl != 0) {
					while (_marginEl > _activeRange) {
						_activeRange = (_n * _width) -_section-1 + _options.innerMargin;
						_n++;
					}
				}
				var _a  = (_activeRange+_section+1 + _options.innerMargin)/_width - 1;
				jQuery('a',_slideNum).eq(_a).addClass('active');
			}
		};
		if (_options.slideNum && !_options.step) {
			jQuery.fn.galleryScroll.numListCreate(jQuery(_options.slideNum, _this), _liSum, _gWidth,_lastSection);
			jQuery.fn.galleryScroll.numListActive(_margin, jQuery(_options.slideNum, _this),_gWidth,_lastSection);
			numClick();
		};
		function numClick() {
			jQuery(_options.slideNum, _this).find('a').click(function(){
				jQuery(_options.btPrev,_this).removeClass('prev-'+_options.disableClass);
				jQuery(_options.btNext,_this).removeClass('next-'+_options.disableClass);
				
				var _indexNum = jQuery(_options.slideNum, _this).find('a').index(jQuery(this));
				_margin = (_step*_indexNum) - _options.innerMargin;
				f=0; _f2=0;
				if (_indexNum == 0) _f2=1;
				if (_margin + _step > _liSum) {
					_margin = _margin - (_margin - _liSum) - _step + _options.innerMargin;
					if (!_options.circleSlide) jQuery(_options.btNext, _this).addClass('next-'+_options.disableClass);
				}
				_animatedBlock.animate({marginLeft: -_margin + "px"}, {queue:false, duration: _options.duration});
				
				if (!_options.circleSlide && _margin==0) jQuery(_options.btPrev,_this).addClass('prev-'+_options.disableClass);
				jQuery.fn.galleryScroll.numListActive(_margin, jQuery(_options.slideNum, _this),_gWidth,_lastSection);
				
				if (_timerSlide) {
					clearTimeout(_timerSlide);
					_timerSlide = setTimeout(function(){
						autoSlide(_options.autoSlide)
					}, _options.autoSlide);
				}
				return false;
			});
		};
		jQuery(window).resize(function(){
			_gWidth = _holderBlock.width();
			_liWidth = jQuery(_options.scrollEl,_animatedBlock).outerWidth(true);
			_liSum = jQuery(_options.scrollEl,_animatedBlock).length * _liWidth;
			if (!_options.step) _step = _gWidth; else _step = _options.step*_liWidth;
			if (_options.slideNum && !_options.step) {
				var _lastSection = 0;
				var _sectionWidth = 0;
				while(_sectionWidth < _liSum)
				{
					_sectionWidth = _sectionWidth + _gWidth;
					if(_sectionWidth > _liSum) {
					       _lastSection = _sectionWidth - _liSum;
					}
				};
				jQuery.fn.galleryScroll.numListCreate(jQuery(_options.slideNum, _this), _liSum, _gWidth,_lastSection);
				jQuery.fn.galleryScroll.numListActive(_margin, jQuery(_options.slideNum, _this),_gWidth,_lastSection);
				numClick();
			};
			//if (_margin == _options.innerMargin) jQuery(this).addClass(_options.disableClass);
			if (_liSum - _gWidth  < _margin - _options.innerMargin) {
				if (!_options.circleSlide) jQuery(_options.btNext, _this).addClass('next-'+_options.disableClass);
				_animatedBlock.animate({marginLeft: -(_liSum - _gWidth + _options.innerMargin)}, {queue:false, duration: _options.duration});
			};
		});
	});
};

// gallery function
jQuery.fn.galleryCircle = function(_options){
	// defaults options
	var _options = jQuery.extend({
		btPrev: 'a.up',
		btNext: 'a.down',
		holderList: 'div.mask',
		scrollElParent: '>ul',
		scrollEl: '>li',
		numHolder: false,
		numCreate: false,
		step: 1,
		innerMargin: 0,
		curPage: false,
		onClick: null,
		easing: 'swing',
		switchTime: false,
		duration : 650
	},_options);

	return this.each(function(){
		var _this = jQuery(this);
		var _next = jQuery(_options.btNext, _this).length ? jQuery(_options.btNext, _this) : false;
		var _prev = jQuery(_options.btPrev, _this).length ? jQuery(_options.btPrev, _this) : false;
		var _holderList = jQuery(_options.holderList, _this);
		var _scrollElParent = jQuery(_options.scrollElParent, _holderList);
		var _scrollEl = jQuery(_options.scrollEl, _scrollElParent);
		var _numHolder = false ;
		if (_options.numHolder) _numHolder = jQuery(_options.numHolder, _this).length ? jQuery(_options.numHolder, _this) : false;
		var _step, _t = null;
		var _heightSum = 0;
		_scrollEl.each(function(){_heightSum += jQuery(this).outerHeight(true);})
		var _startPosition = _scrollEl.index(_scrollEl.filter('.active'));
		if (_startPosition==-1) _startPosition=0;
		_scrollEl.removeClass('active');
		var _easing = _options.easing;

		if (!_options.step) _step = _holderList.innerHeight();
		var _margin = _heightSum;
		_scrollElParent.append(_scrollEl.clone(true));
		_scrollElParent.prepend(_scrollEl.clone(true));

		var _offsetStartPosition =0;
		_offsetStartPosition = culcOffset(_startPosition);

		_scrollElParent.css('marginTop', (-_margin+_options.innerMargin-_offsetStartPosition));

		//auto rotation
		if (_options.switchTime) {
			_t = setTimeout(function(){
				nextSlides();
			},_options.switchTime);
		}
		
		//button next "click"
		if (_next) {
			_next.click(function(){
				if (!_scrollElParent.is(':animated')) {
					if (jQuery.isFunction(_options.onClick)) _options.onClick.apply(_this);
					nextSlides();
				}
				return false;
			});
		}

		//button prev "click"
		if (_prev) {
			_prev.click(function(){
				if (!_scrollElParent.is(':animated')) {
					if (jQuery.isFunction(_options.onClick)) _options.onClick.apply(_this);
					prevSlides();
				}
				return false;
			});
		}

		//curent position
		function getCurElIndex(){
			var _curMargin = parseInt(_scrollElParent.css('marginTop')) + _heightSum - _options.innerMargin;
			for(i=0; i < _scrollEl.length; i++){
				if (_curMargin == 0) return i;
				if (_curMargin <= _options.innerMargin) _curMargin += _scrollEl.eq(i).innerHeight();
				else _curMargin -= _scrollEl.eq(i).innerHeight();
				if (_curMargin == _options.innerMargin) return i+1;
			}
		}

		// offset of gallery if when activ element not first at start 
		function culcOffset(_ind){
			var _tmpcounter=0;
			var _pos=0;
			while (_tmpcounter < _ind){
				_pos += _scrollEl.eq(_tmpcounter).outerHeight(true);
				_tmpcounter++;
			};
			return _pos;
		}

		//go next slide
		function nextSlides(){
			if (_t) clearTimeout(_t);
			if (_options.step) {
				_curElIndex = getCurElIndex();
				_step = _scrollEl.eq(_curElIndex).innerHeight();
			};
			_margin = -parseInt(_scrollElParent.css('marginTop'));
			_margin += _step;
			
			_scrollElParent.animate({'marginTop':(-_margin+_options.innerMargin)}, {duration:_options.duration, easing: _easing, complete:function(){
				if (_margin >= _heightSum*2) {
					_margin = _heightSum + (_margin - _heightSum*2);
				}
				_scrollElParent.css({'marginTop':-_margin+_options.innerMargin});
				jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);

				//autoslide
				if (_options.switchTime) {
					_t = setTimeout(function(){
						nextSlides();
					},_options.switchTime)
				}
			}});
		}

		//go prev slide
		function prevSlides(){
			if (_t) clearTimeout(_t);
			if (_options.step) {
				_curElIndex = getCurElIndex();
				if (_curElIndex == 0) _curElIndex= _scrollEl.length;
				_step = _scrollEl.eq(_curElIndex-1).innerHeight();
			};
			_margin = -parseInt(_scrollElParent.css('marginTop'));
			_margin -= _step;
			_scrollElParent.animate({'marginTop':(-_margin+_options.innerMargin)}, {duration:_options.duration, easing: _easing, complete:function(){
				if (_margin < _heightSum) {
					_margin = _heightSum*2 - (_heightSum - _margin);
				}
				_scrollElParent.css({'marginTop':-_margin+_options.innerMargin});
				jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);

				//autoslide
				if (_options.switchTime) {
					_t = setTimeout(function(){
						nextSlides();
					},_options.switchTime)
				}
			}});
		}

		// Number list Create
		jQuery.fn.galleryCircle.numListCreate = function(_numHolder, _scrollEl){
			var _numListElC = '';
			for(var i=0; i<_scrollEl.length; i++){
				_numListElC += '<li><a href="">'+(i+1)+'</a></li>';
			}
			jQuery(_numHolder).html('<ul>'+_numListElC+'</ul>');
		};

		// Number list Activate
		jQuery.fn.galleryCircle.numListActive = function(_numHolder, _scrollEl){
			_curElIndex = getCurElIndex();
			if (jQuery(_options.curPage, _this).length && _options.curPage) jQuery(_options.curPage, _this).text('Pagina '+(getCurElIndex()+1)+'/'+_scrollEl.length);
			if (_numHolder) {
				jQuery('a',_numHolder).removeClass('active');
				jQuery('a',_numHolder).eq(_curElIndex).addClass('active');
			}
		};

		//click on control elemens
		function numClick() {
			jQuery(_options.numHolder, _this).find('a').click(function(){
				if (_t) clearTimeout(_t);
				var _aList = jQuery(_options.numHolder, _this).find('a');
				var _index = _aList.index(jQuery(this));
				_margin = _heightSum + _index * _scrollEl.outerHeight(true);
				_scrollElParent.animate({'marginTop':(-_margin+_options.innerMargin)}, {duration:_options.duration, easing: _easing, complete:function(){
					if (_margin >= _heightSum*2) {
						_margin = _heightSum + (_margin - _heightSum*2);
					}
					_scrollElParent.css({'marginTop':-_margin+_options.innerMargin});
					_aList.removeClass('active').eq(_index).addClass('active');

					//autoslide
					if (_options.switchTime) {
						_t = setTimeout(function(){
							nextSlides();
						},_options.switchTime)
					}
				}});
				return false;
			});
		};

		// init creating num list
		if (_options.numCreate) jQuery.fn.galleryCircle.numListCreate(_numHolder, _scrollEl);

		// pagination first init (example Page 2/6)
		if (jQuery(_options.curPage, _this).length && _options.curPage) jQuery(_options.curPage, _this).text('Pagina '+(getCurElIndex()+1)+'/'+_scrollEl.length);

		// init activate num list item and init numClick()
		if (_options.numHolder) {
			jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);
			numClick();
		}
	});
};


//create jQuery plugin
jQuery.fn.slideshow = function(options){return new slideshow(this, options);}

//constructor
function slideshow(obj, options){this.init(obj,options)}

//prototype
slideshow.prototype = {
	init:function(obj, options) {
		this.options = jQuery.extend({
			slides:'ul.gallery > li',
			nextBtn:'a.next',
			prevBtn:'a.prev',
			pagingHolder:'ul.slider',
			pagingTag:'li',
			createPaging:false,
			autoPlay:false,
			autoHeight:false,
			dynamicLoad:false,
			imgAttr:'alt',
			effect:'slideX',//fade, slideX, slideY,
			startSlide:false,
			switchTime:5000,
			animSpeed:700
		},options);
		
		this.mainHolder = jQuery(obj);
		this.slides = jQuery(this.options.slides,this.mainHolder);		
		this.nextBtn = jQuery(this.options.nextBtn,this.mainHolder);
		this.prevBtn = jQuery(this.options.prevBtn,this.mainHolder);
		this.dynamicLoad = this.options.dynamicLoad;
		this.imgAttr = this.options.imgAttr;
		this.animSpeed = this.options.animSpeed;
		this.switchTime = this.options.switchTime;
		this.effect = this.options.effect;
		this.autoPlay = this.options.autoPlay;
		this.autoHeight = this.options.autoHeight;
		this.previous = -1;
		this.loadingFrame = 1;
		this.busy = false;
		this.direction = 1;
		this.timer;
		this.pagingArray = new Array;
		this.loadArray = new Array;
		this.preloader = new Array;
		this.slidesParent = this.slides.eq(0).parent();
		this.slideW = this.slidesParent.width();
		this.slideH = this.slidesParent.height();
		
		(function(){
			if (this.options.startSlide) this.current = this.options.startSlide
			else {
				var active = -1;
				for(var i = 0; i< this.slides.length-1; i++) {
					if (this.slides.eq(i).hasClass('active')) {
						active = i;
						break;
					}
				}
				if (active != -1) this.current = active;
				else this.current = 0;
			}
		}).apply(this);
		
		this.initPaging();
		this.setStyles();
		this.bindEvents();
		this.showSlide();
	},
	
	initPaging:function(){
		var obj = this;
		this.pagingHolder = jQuery(this.options.pagingHolder,this.mainHolder);
		
		if (this.options.createPaging) {
			this.pagingHolder.each(function(i){
				var _this = jQuery(this);
				_this.empty();
				var list = jQuery('<ul>');
				for (var i = 0; i < obj.slides.length; i++) jQuery('<li><a href="#">' + (i + 1) + '</a></li>').appendTo(list);
				_this.append(list);
			});
		}
		
		this.paging = jQuery(this.options.pagingTag, this.pagingHolder);
		var ratio = Math.ceil(this.paging.length / this.slides.length);
		for (var i = 0; i < ratio; i++) {
			this.pagingArray.push(this.paging.slice(i*this.slides.length, (i*this.slides.length)+this.slides.length));
		}
	},
	
	setStyles:function(){
		//loader
		if (this.dynamicLoad) {
			this.loader = jQuery('<div class="loader">');
			this.loaderDiv = jQuery('<div>').appendTo(this.loader)
			this.loader.append(this.loaderDiv).appendTo(this.slidesParent);
		}
		// auto height
		if (this.autoHeight) {
			this.slides.eq(this.current).parent().css({height:this.slides.eq(this.current).outerHeight(true)});
		}
		//slides
		if (this.effect == 'fade') {
			this.slides.css({display:'none'});
			this.slides.eq(this.current).css({display:'block'});
		} else if (this.effect == 'slideX'){
			this.slides.css({display: 'none',left:-this.slideW});
			this.slides.eq(this.current).css({display:'block',left:0});
		} else if (this.effect == 'slideY'){
			this.slides.css({display:'none',top:-this.slideH});
			this.slides.eq(this.current).css({display:'block',top:0});
		}
	},
	
	bindEvents:function(){
		var obj = this;
		this.nextBtn.bind('click',function(){
			if (!obj.busy) obj.nextSlide();
			return false;
		});
		
		this.prevBtn.bind('click',function(){
			if (!obj.busy) obj.prevSlide();
			return false;
		});
		
		for (var i = 0; i < this.pagingArray.length; i++) {
			this.pagingArray[i].each(function(i){
				jQuery(this).bind('click',function(){
					if (i != obj.current && !obj.busy) {
						obj.previous = obj.current;
						obj.current = i;
						if (obj.previous > i) obj.direction = -1
						else obj.direction = 1;
						obj.showSlide();
					}
					return false;
				});
			});
		}
		
		if (this.dynamicLoad) this.loader.bind('click',function(){
			obj.abortLoading();
		});
	},
	
	nextSlide:function(){
		this.previous = this.current;
		if (this.current < this.slides.length-1) this.current++
		else this.current = 0;
		this.direction = 1;
		this.showSlide();
	},
	
	prevSlide:function(){
		this.previous = this.current;
		if (this.current > 0) this.current--
		else this.current = this.slides.length-1;
		this.direction = -1;
		this.showSlide();
	},
	
	showSlide:function(){
		var obj = this;
		var _current = this.current;
		this.busy = true;
		clearTimeout(this.timer);
		
		if (typeof this.loadArray[_current] != 'undefined' || !this.dynamicLoad) {
			//slide already loaded
			this.switchSlide();
		
		} else {
			//slide not loaded
			this.showLoading();
			var images = jQuery(this.dynamicLoad,this.slides.eq(this.current));
			if (images.length) {
				var counter = 0;
				images.each(function(){
					var preloader = new Image;
					obj.preloader.push(preloader);
					var img = jQuery(this);
					preloader.onload = function(){
						counter++;
						checkImages();
					}
					preloader.onerror = function(){
						//ignore errors
						counter++;
						checkImages();
					}
					preloader.src = img.attr(obj.imgAttr);
				});
				
				function checkImages(){
					if (counter == images.length) {
						images.each(function(){
							var img = jQuery(this);
							img.attr('src',img.attr(obj.imgAttr));
						});
						successLoad();
					}
				}
				
			} else successLoad();
		}
		
		function successLoad(){
			obj.loadArray[_current] = 1;
			obj.hideLoading();
			obj.switchSlide();
		}
	},
	
	switchSlide:function(){
		var obj = this;
		
		if (this.previous != -1) {
			var nextSlide = this.slides.eq(this.current);
			var prevSlide = this.slides.eq(this.previous);
			
			if (this.autoHeight) this.slides.eq(this.current).parent().animate({height:this.slides.eq(this.current).outerHeight(true)},this.animSpeed);
			if (this.effect == 'fade') {
				nextSlide.css({display:'block',opacity:0}).animate({opacity:1},this.animSpeed,function(){
					jQuery(this).css({opacity:'auto'});
				});
				prevSlide.animate({opacity:0},this.animSpeed,callback);
			} else if (this.effect == 'slideX'){
				nextSlide.css({display:'block',left:this.slideW*this.direction}).animate({left:0},this.animSpeed);
				prevSlide.animate({left:-this.slideW*this.direction},this.animSpeed+10,callback);
			} else if (this.effect == 'slideY'){
				nextSlide.css({display:'block',top:this.slideH*this.direction}).animate({top:0},this.animSpeed);
				prevSlide.animate({top:-this.slideH*this.direction},this.animSpeed+10,callback);
			}
		} else {
			if (this.autoPlay) this.startAutoPlay();
			this.busy = false;
		}
		
		this.refreshStatus();
		
		function callback(){
			prevSlide.css({display:'none'});
			if (obj.autoPlay) obj.startAutoPlay();
			obj.busy = false;
		}
	},
	
	refreshStatus:function(){
		for (var i = 0; i < this.pagingArray.length;i++) {
			this.pagingArray[i].eq(this.previous).removeClass('active');
			this.pagingArray[i].eq(this.current).addClass('active');
		}
		this.slides.eq(this.previous).removeClass('active');
		this.slides.eq(this.current).addClass('active');
	},
	
	showLoading:function(){
		var obj = this;
		this.loader.show();
		clearInterval(this.loadingTimer);
		obj.loadingTimer = setInterval(animateLoading, 66);
		
		function animateLoading(){
			obj.loaderDiv.css('top', obj.loadingFrame * -40);
			obj.loadingFrame = (obj.loadingFrame + 1) % 12;
		}
	},
	
	hideLoading:function(){
		this.loader.hide();
		clearInterval(this.loadingTimer);
	},
	
	abortLoading:function(){
		this.busy = false;
		this.hideLoading();
		this.current = this.previous;
		for (var i = 0; i < this.preloader.length; i++) {
			this.preloader[i].onload = null;
			this.preloader[i].onerror = null;
		}
		if (this.autoPlay) this.startAutoPlay();
	},
	
	startAutoPlay:function(){
		var obj = this;
		clearTimeout(obj.timer);
		obj.timer = setTimeout(function(){
			obj.nextSlide();
		},obj.switchTime);
	}
};

//lightbox plugin
jQuery.fn.modalPopup = function(options){return new modalPopup(jQuery(this).eq(0),options)}
function modalPopup(link, options) {this.init(link,options)}
modalPopup.prototype = {
	init:function(link,options){
		var el = this;
		//options
		el.options = jQuery.extend({
			fadeSpeed:300,
			closer:'a.close',
			scroll:true,
			wrapper:'#mainContent',
			IE:true,
			zIndex:9999,
			beforeOpen:null
		},options);	
		//popup & default css styles
                
		if (jQuery.browser.msie && el.options.IE) el.popup = jQuery(link.attr('href')).css({visibility:'hidden'})
		else el.popup = jQuery(link.attr('href')).css({opacity:0,visibility:'hidden'});
		if (el.options.zIndex) el.popup.css({zIndex : el.options.zIndex});
		el.closer = jQuery(el.popup.find(el.options.closer));
		el.popup.visible = false;
		modalPopup.prototype.activePopup = false;
		if (!modalPopup.prototype.firstRun) {
			modalPopup.prototype.firstRun = 'done';
			if (jQuery.browser.msie && jQuery.browser.version < 7) modalPopup.prototype.selects = jQuery('select');
			//create fader
                        /*if (jQuery.browser.msie && jQuery.browser.version <= 7)
                        {
                            if (!jQuery('#fader').length) jQuery('.spanContainer-3').append('<div id="fader"></div>');
                            }
                        else
                        {
                            if (!jQuery('#fader').length) jQuery('body').append('<div id="fader"></div>');
                            }*/
			if (!jQuery('#fader').length) jQuery('body').append('<div id="fader"></div>');
			modalPopup.prototype.fader = jQuery('#fader');
			modalPopup.prototype.fader.css({position:'absolute',top:0,left:0,background:'#000',opacity:0,display:'none'});	
			if (el.options.zIndex) modalPopup.prototype.fader.css({zIndex : 9998});
			modalPopup.prototype.wrapper = jQuery(el.options.wrapper);
			//fader click event
			modalPopup.prototype.fader.click(function(){
				if (modalPopup.prototype.activePopup == false) el.hideFader()
				else modalPopup.prototype.activePopup.hidePopup(function(){el.hideFader()});
				return false;
			});
			//esc event
			jQuery(document).keydown(function (e) {
				if (e.keyCode == 27) {
					if (modalPopup.prototype.activePopup == false) el.hideFader()
					else modalPopup.prototype.activePopup.hidePopup(function(){el.hideFader()});
					return false;
				}
			});
		}
		
		el.wrapper = modalPopup.prototype.wrapper;
		
		if (jQuery.browser.msie && jQuery.browser.version < 7) {
			el.popupSelects = jQuery('select',el.popup);
			modalPopup.prototype.selects = modalPopup.prototype.selects.not(el.popupSelects);
		}
		
		//open event
		link.click(function(){
			el.show();
			return false;
		});
		//close event
		el.closer.click(function(){
			el.close();
			return false;
		});
		//resize event
		jQuery(window).resize(function(){
			if (el.popup.visible) el.positioning(false);
		});
		if (el.options.scroll) {
			jQuery(window).scroll(function(){
				el.positioning(true);
			});
		}
	},
	
	close:function(){
		var el = this;
		el.hidePopup(function(){el.hideFader()});
	},
	
	show:function(){
		var el = this;
		if (typeof el.options.beforeOpen === 'function') el.options.beforeOpen();
		if (modalPopup.prototype.activePopup == el) {return false;}
		if (modalPopup.prototype.activePopup) {
			modalPopup.prototype.activePopup.hidePopup(function(){
				el.showPopup()
				el.positioning(true);
			});
		} else {
			el.showFader(function(){el.showPopup()});
			el.positioning(true);
		} 
	},
	
	showPopup:function(){
		var el = this;
		el.popup.visible = true;
		modalPopup.prototype.activePopup = el;
		if (jQuery.browser.msie && el.options.IE) el.popup.css({visibility:'visible'})
		else el.popup.stop().css({'visibility':'visible'}).animate({opacity:1},el.options.fadeSpeed)
	},
	hidePopup:function(callback){
		var el = this;
		if (jQuery.browser.msie && el.options.IE) {
			el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
			el.popup.visible = false;
			modalPopup.prototype.activePopup = false;
			if (jQuery.isFunction(callback)) callback();
		} else {
			el.popup.stop().animate({opacity:0},el.options.fadeSpeed,function(){
				el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
				el.popup.visible = false;
				modalPopup.prototype.activePopup = false;
				if (jQuery.isFunction(callback)) callback();
			});
		}
	},
	showFader:function(callback){
		var el = this;
		el.fader.stop().css({display:'block'}).animate({opacity:0.5},el.options.fadeSpeed,function(){
			if (jQuery.isFunction(callback)) callback();
		});
		if (jQuery.browser.msie && jQuery.browser.version < 7) modalPopup.prototype.selects.css({'visibility': 'hidden'});
	},
	hideFader:function(){
		var el = this;
		el.fader.stop().animate({opacity:0},el.options.fadeSpeed,function(){
			el.fader.css({display:'none'});
			if (jQuery.browser.msie && jQuery.browser.version < 7) modalPopup.prototype.selects.css({'visibility': 'visible'});
		});
	},
        
        positioning:function(openFlag){
		var el = this;
		//x offset
		var windowW = jQuery(window).width();
		var popupW = el.popup.outerWidth();
		var wrapperW = el.wrapper.outerWidth();
		//alert(wrapperW + " " + popupW + " " + (wrapperW/2 - popupW/2));
		if (windowW < wrapperW) {
			el.popup.css({left:wrapperW/2-popupW/2})
			el.fader.css({width:wrapperW});
		} else {
			 el.popup.css({left:windowW/2-popupW/2});
			 el.fader.css({width:windowW})
		}
		//y offset
		var docH;
		var windowH = jQuery(window).height();
		var wrapperH = el.wrapper.outerHeight();
		//var wrapperH = $(document).height();
		if (windowH < wrapperH) docH = wrapperH
		else docH = windowH;
		
		var popupH = el.popup.outerHeight();
		if (openFlag) {
			var popupH = el.popup.outerHeight();
			if (popupH < windowH) el.popup.css({top:windowH/2-popupH/2+jQuery(window).scrollTop()});
			else if (jQuery(window).scrollTop()+popupH > docH){
				//el.popup.css({top:docH-popupH});
                                el.popup.css({top:0});
			} else {
				el.popup.css({top:jQuery(window).scrollTop()});
			}
		}
		el.fader.css({height:docH});
	}
	/*positioning:function(openFlag){
	
                	var el = this;
		//x offset
		var windowW = jQuery(window).width();
		var popupW = el.popup.outerWidth();
		var wrapperW = el.wrapper.outerWidth();
		alert(wrapperW + " " + popupW + " " + (wrapperW/2 - popupW/2));
		if (windowW < wrapperW) {
                        if (jQuery.browser.msie)
                        {
                            el.popup.css({left:wrapperW/2-popupW/2});
                        }
                        else
                        {
                            el.popup.css({left:wrapperW/2-popupW/2});
                        }
			el.fader.css({width:wrapperW});
		} else {
                        if (jQuery.browser.msie)
                        {
                            el.popup.css({left:windowW/2-popupW/2});
                        }
                        else
                        {
                            el.popup.css({left:windowW/2-popupW/2});
                        }
			el.fader.css({width:windowW})
		}
                
                //el.popup.css({left:25});
                el.fader.css({width:windowW});
		//y offset
		var docH;
		var windowH = jQuery(window).height();
		//var wrapperH = el.wrapper.outerHeight();
		var wrapperH = $(document).height();
                if (windowH < wrapperH) docH = wrapperH
		else docH = windowH;

		/*var popupH = el.popup.outerHeight();
		if (openFlag) {
			var popupH = el.popup.outerHeight();
			if (popupH < windowH)
                        {
                            if(jQuery.browser.msie)
                            {
                                el.popup.css({top:(windowH/2-popupH/2+jQuery(window).scrollTop())-170});
                            }
                            else
                            {
                                el.popup.css({top:(windowH/2-popupH/2+jQuery(window).scrollTop())-190});
                            }
                        }
                        
			else if (jQuery(window).scrollTop()+popupH > docH){
				el.popup.css({top:docH-popupH});
			} else {
				el.popup.css({top:jQuery(window).scrollTop()});
			}
		}
                el.popup.css({top:0});
		el.fader.css({height:docH});
	}*/
};

// mobile browsers detect
browserPlatform = {
	platforms: [
		{
			// Blackberry <5
			uaString:['BlackBerry','midp'],
			cssFile:'blackberry.css'
		},
		{
			// Symbian phones
			uaString:['symbian','midp'],
			cssFile:'symbian.css'
		},
		{
			// Opera Mobile
			uaString:['opera','mobi'],
			cssFile:'opera.css'
		},
		{
			// IE Mobile <6
			uaString:['msie','ppc'],
			cssFile:'ieppc.css'
		},
		{
			// IE Mobile 6+
			uaString:'iemobile',
			cssFile:'iemobile.css'
		},
		{
			// Palm WebOS
			uaString:'webos',
			cssFile:'webos.css'
		},
		{
			// Android
			uaString:'Android',
			cssFile:'android.css'
		},
		{
			// Blackberry 6+
			uaString:['BlackBerry','6.0','mobi'],
			cssFile:'blackberry6.0.css'
		},
		{
			// iPad
			uaString:'ipad',
			cssFile:'ipad.css',
			miscHead:''
		},
		{
			// iPhone and other webkit browsers
			uaString:['safari','mobi'],
			cssFile:'safari.css',
			miscHead:''
		}
	],
	options: {
		cssPath:'/SiteCollectionDocuments/css/',
		mobileCSS:'allmobile.css'
	},
	init:function(){
		this.checkMobile();
		this.parsePlatforms();
		return this;
	},
	checkMobile: function() {
		if(this.uaMatch('mobi') || this.uaMatch('midp') || this.uaMatch('ppc') || this.uaMatch('webos')) {
			this.attachStyles({cssFile:this.options.mobileCSS});
		}
	},
	parsePlatforms: function() {
		for(var i = 0; i < this.platforms.length; i++) {
			if(typeof this.platforms[i].uaString === 'string') {
				if(this.uaMatch(this.platforms[i].uaString)) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			} else {
				for(var j = 0, allMatch = true; j < this.platforms[i].uaString.length; j++) {
					if(!this.uaMatch(this.platforms[i].uaString[j])) {
						allMatch = false;
					}
				}
				if(allMatch) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			}
		}
	},
	attachStyles: function(platform) {
		if(platform.cssFile) {
			document.write('<link rel="stylesheet" href="' + this.options.cssPath + platform.cssFile + '" type="text/css"/>');
		}
		if(platform.miscHead) {
			document.write(platform.miscHead);
		}
	},
	uaMatch:function(str) {
		if(!this.ua) {
			this.ua = navigator.userAgent.toLowerCase();
		}
		return this.ua.indexOf(str.toLowerCase()) != -1;
	}
}.init();



//get URL parameters
$.extend({
    getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        } 
        
        return vars;
    },
    
    getUrlVar: function(name){
        return $.getUrlVars()[name];
    }
    
});


//adjust right hand bar height

function adjustRightBarHeight()
{
        //$('.spanContainer-3').css("height", "100%");
        var mainHeight = $('.spanContainer-3').outerHeight();
        //var barHeight = $('.spanContainer-1').outerHeight();
        
        if($('.spanContainer-1').eq(1))
        {
            //mainHeight = $('.spanContainer-3').outerHeight();
            barHeight = $('.spanContainer-1').eq(1).outerHeight();
            
        }
        
        if (mainHeight >= barHeight)
        {
            $('.spanContainer-1').css("height", mainHeight + "px");
        }
        
        else
        {
            $('.spanContainer-3').css("height", barHeight-35 + "px");
            /*if (barHeight == 586 || barHeight == 831)
            {
                $('.spanContainer-1').css("height", mainHeight + "px");
            }*/
            $('.spanContainer-1').css("height", "100%");
        }
}

function initMainNav()
{
    $('div.topLvlNav').children('ul').attr('id', 'nav');
    
    $('div.topLvlNav').append("<a href=\"/en-US/Pages/Worldwide.aspx\" class=\"worldwide-link\">Worldwide</a>");
    
    $.ajax({
        url:"/SiteCollectionDocuments/xml/mainNav.xml",
        type: "GET",
        dataType: "xml",
        complete: createNavDropDowns,
        contentType: "text/xml; charset=\"utf-8\""
    });

    
}

function createNavDropDowns(xData, status)
{
    $('#nav').children('li').each(function()
    {
        var linkText = $(this).find(">:first-child").text();
        $(this).find(">:first-child").empty();
        $(this).find(">:first-child").append($("<span>" + linkText + "</span>"));
        
        if($(this).text() == "Home" && $(this).hasClass('current'))
        {
            $(this).attr('class', 'active-home');
        }
        else if($(this).text() == "Home")
        {
            $(this).attr('class', 'link-home');
        }
        
        var tabContent = getNavContent(xData, $(this).find(">:first-child").text());
        if(tabContent)
        {
            if($(this).hasClass('current'))
            {
                $(this).attr('class', 'current whith-drop');
            }
            else
            {
                $(this).attr('class', 'whith-drop');
            }
            
            
            
            $(this).append($(tabContent)); 
        }
        
    });
    

}

function getNavContent(xData, menuItem)
{
    var returnText = "";
    $(xData.responseXML).find("MenuItem").each(function()
    {
        
        if($(this).attr("name") == menuItem)
        {
            if(!$(this).text())
            {
                returnText = "";
            }
            else
            {
                returnText = $(this).text();
            }
            
        }
    });
    
    return returnText;
}


function ie7Fix()
{
    if (jQuery.browser.msie && jQuery.browser.version <= 7)
    {
        $(function() {
            var zIndexNumber = 10000;
            $('div').each(function() {
                                        
                if ($(this).attr('class') == 'modal' || $(this).attr('class') == 'modal modal2' || $(this).attr('class') == 'drop')
                {
                    $(this).css('zIndex', 9999);
                }
                else if ($(this).attr('id') == 'fader')
                {
                    $(this).css('zIndex', 1001);
                }
                else
                {
                    $(this).css('zIndex', zIndexNumber);
                    zIndexNumber -= 10;
                }
                                        
            });  
                                
        });
    }
}


function isContained(urlString, testString) {
	var tmpStr = urlString.toLowerCase();
	var tmptestStr = testString.toLowerCase();
	return tmpStr.indexOf(tmptestStr);
}

function initTimer()
{
    window.setInterval(rotate, 6000);    
}

function rotate()
{
    var popupOpen = false;
    $('.popup').each(function(){
        if($(this).css('display') == 'block')
        {
            popupOpen = true;
        }
    });
    
    $('.modal').each(function() {
        if($(this).css('visibility') == 'visible')
        {
            popupOpen = true;
        }
    });
    
    
    if(!popupOpen)
    {
        $('.next').click();
    }
}

