// CAROUSELS

var carousels=[];
j(window).load(function() {

        /* FIX NEWS/EVENTS DISPLAY ON FRONTEND */

        var hasMonthTable=false;

        try {
            monthTable=monthTable;
            hasMonthTable=true;
        } catch(err) {
            monthTable=false;
        }

        // news
        j('.news h3.head').each(function(ix,el) {
                var temp=j(el).html();
		if (temp.indexOf(' ')>=0) { // only do if spaces are present, otherwise date is a number-only format and doesn't need this
			temp=temp.split(' ');
			// translate month name
			if (hasMonthTable) {
				temp[0]=monthTable[temp[0]];
			}
			// add "20" to year if it's a 2-digit year and only if month table is missing (only on US site)
			if (temp[2].length==2) {
				temp[2]='20'+temp[2];
			}
			j(el).html(temp.join(' '));
		}
        });
        // events
        j('.event .month').each(function(ix,el) {
                // translate month name
                if (hasMonthTable) {
                        var temp=j(el).html();
                        temp=temp.split(' ');
                        temp[0]=monthTable[temp[0]];
                        j(el).html(temp.join(' '));
                }
        });
        // replace characters with HTML entities
        j('#smallFeature.carousel .panel p').each(function(ix,el) {
                j(el).html(j(el).html().replace('�','&#0145;').replace('�','&#0146;').replace('�','&#0147;').replace('�','&#0148;').replace('�','&#0153;').replace('�','&#0174;'));
        });

        try {
            Cufon.replace('.cufon',{ fontFamily: 'Meta' });
        } catch(err) {}

	j('.carousel').each(function(ix0,el0) {

		if (j(el0).children('.panel').length>1) {

			carousels[ix0]={
				element: el0,
				isAnimating: false,
				numPanels: 0,
				panels: j(el0).find('.panel'),
				width: 0,
				oldPanel: 0,
				cPanel: 0,
				rotateTimer: 0,
				rotateDelay: Number(j(el0).attr('delay'))*1000,
				animType: (j(el0).attr('anim')==undefined)?'fade':j(el0).attr('anim'),
				animTime: Number(j(el0).attr('animtime'))*1000,
				navType: j(el0).attr('nav')
			}

			j(el0).addClass('jsEnabled'); /* undoes hiding of all but first feature */

			carousels[ix0].numPanels=carousels[ix0].panels.length;
			// set curr feature to last prior to start
			carousels[ix0].cPanel=0;//carousels[ix0].numPanels-1;
			carousels[ix0].width=j(el0).width();

                        if (carousels[ix0].navType=='swipe' || (j(el0).hasClass('mainFeature') && isIOS)) { //iOS uses swipe on main carousel
    			    carousels[ix0].animType='swipe';
			    j(el0).addClass('iOS');
			    iOSareaMask=j(el0)[0];
			    if (navigator.userAgent.match(/like Mac OS X/i)) { //iOS use different events
				j(el0).bind('touchstart',beginDrag);
				j(el0).bind('touchmove',updatePos);
				j(document).bind('touchend',endDrag);
			    } else {
				j(iOSareaMask).bind('mousedown',beginDrag);
				j(el0).bind('mousemove',updatePos);
				j(document).bind('mouseup',endDrag);
			    }
                        }

			// AUTOROTATE controls
			if (carousels[ix0].animType!='swipe' && carousels[ix0].rotateDelay!=0) {
			    j(el0).mouseenter(function() {
				    clearTimeout(carousels[ix0].rotateTimer);
				    j(el0).children('.carouselNav').children('.bPlayPause').children('.bPlay').css({ display: 'block' });
				    j(el0).children('.carouselNav').children('.bPlayPause').children('.bPause').css({ display: 'none' });
			    });
			    j(el0).mouseleave(function() {
				    clearTimeout(carousels[ix0].rotateTimer);
				    if (overlayIsOpen!=true) {
					carousels[ix0].rotateTimer=setTimeout(function() {
					    rotate(ix0);
					}, carousels[ix0].rotateDelay);
				    }
				    j(el0).children('.carouselNav').children('.bPlayPause').children('.bPlay').css({ display: 'none' });
				    j(el0).children('.carouselNav').children('.bPlayPause').children('.bPause').css({ display: 'block' });
			    });
			}

			// initialize carousel
			switch (carousels[ix0].animType) {
				case 'swipe':
					j(el0).find('.panel').wrapAll('<div class="swipeWrapper"/>');
					iOSareaContent=j(el0).children('.swipeWrapper')[0];
					dragTimer=setInterval(updateScrollArea,1000/frameRate);
					//add shadows L and R
					j(iOSareaContent).append('<img id="leftShadow" src="/_admin/js/overlay-apr2011/shadowML.png"/><img id="rightShadow" src="/_admin/js/overlay-apr2011/shadowMR.png"/>')
				break;
				case 'slide':
				case 'fullslide':
				case 'crossfade':
					// nothing needed
				break;
				case 'fade':
				default:
					j(el0).children('.carouselNav').before('<div class="fadeCover"></div>');
					j(el0).children('.fadeCover').css({
						display: 'none',
						opacity: 0,
						width: j(carousels[ix0].panels[carousels[ix0].oldPanel]).width()+'px',
						height: j(carousels[ix0].panels[carousels[ix0].oldPanel]).height()+'px'
					});
			}
			// initialize feature panels
			j(el0).find('.panel').each(function(ix,el) {
				switch (carousels[ix0].animType) {
					case 'swipe':
						j(el).css({ left: (ix*j(el0).width())+'px' });
					break;
					case 'slide':
						if (ix) {
							j(el).css({ left: '1000px' });
						}
					break;
					case 'fullslide':
						j(el).css({ left: (ix*j(el0).width())+'px' });
					break;
					case 'crossfade':
						j(el).css({ opacity: 0 });
					break;
					case 'fade':
					default:
						if (ix) {
							j(el).css({ display: 'none' });
						}
				}
				switch (carousels[ix0].navType) {
					case 'count':
						// do nothing, this is done below in feature nav setup since it's only done once, not per panel
					break;
					case 'boxes':
					default:
					    j(el0).find('.carouselNav').append('<div class="carouselNavElement box ' + ((ix)?'off':'on') + '"' + ((ix!=carousels[ix0].numPanels-1)?'':' style="margin-right: 0px;"') + '><img class="off" src="/images/hp-mar2011/nav-box-off.png"/><img class="on" src="/images/hp-mar2011/nav-box-on.png"/></div>');
				}
			});
			//final setup (only for swipe)
			switch (carousels[ix0].animType) {			
				case 'swipe':
					//manually set width of wrapper to match child content width
					j(iOSareaContent).width(j(iOSareaContent).children('.panel').last().position().left+j(iOSareaContent).children('.panel').last().width());
				break;
				default:
			}
			// first view
			if (carousels[ix0].animType!='fullslide' && carousels[ix0].animType!='swipe') {
				doPanelSwitch(ix0,0,false,true);
			}
			// kick off rotation
			if (carousels[ix0].rotateDelay!=0) {
			    carousels[ix0].rotateTimer=setTimeout(function() { rotate(ix0); }, carousels[ix0].rotateDelay);
			}

			// feature nav events
			j(el0).children('.carouselNav').click(function(ev) { ev.preventDefault(); });
			switch (carousels[ix0].navType) {
				case 'count':
					j(el0).children('.carouselNav').append('<div class="carouselNavElement arrowLeft off"><img class="off" src="images/nav-arrow-left-off.png"/><img class="on" src="images/nav-arrow-left-on.png"/></div>');
					j(el0).children('.carouselNav').append('<div class="carouselNavElement stateIndicator"></div>');
					j(el0).children('.carouselNav').append('<div class="carouselNavElement arrowRight off"><img class="off" src="images/nav-arrow-right-off.png"/><img class="on" src="images/nav-arrow-right-on.png"/></div>');
					j(el0).find('.carouselNavElement').each(function(ix,el) {
						disableSelection(el);
						j(el).mouseenter(buttonRollover);
						j(el).mouseleave(buttonRollout);
					});
					j(el0).find('.arrowLeft').children('.on').css({ opacity: 0 });
					j(el0).find('.arrowLeft').click(function (ev) { arrowLeftClick(ev,ix0); });
					j(el0).find('.arrowLeft').bind('touchend',function (ev) { arrowLeftClick(ev,ix0); }); /* iOS catch (otherwise you need to click twice) */
					j(el0).find('.arrowRight').children('.on').css({ opacity: 0 });
					j(el0).find('.arrowRight').click(function (ev) { arrowRightClick(ev,ix0); });
					j(el0).find('.arrowRight').bind('touchend',function (ev) { arrowRightClick(ev,ix0); }); /* iOS catch (otherwise you need to click twice) */
				break;
				case 'boxes':
				default:
					j(el0).children('.carouselNav').children('.carouselNavElement').each(function(ix,el) {
						disableSelection(el);
						j(el).attr('ix',ix);
						j(el).mouseenter(buttonRollover);
						j(el).mouseleave(buttonRollout);
						j(el).click(function (ev) { boxClick(ev,ix0); });
						j(el).bind('touchend',function (ev) { boxClick(ev,ix0); }); /* iOS catch (otherwise you need to click twice) */
					});
			}
			// final width adjustment of carousel nav
			fnbWidthTotal=0;
			j(el0).find('.carouselNavElement').each(function(ix,el) {
				fnbWidthTotal+=j(el).outerWidth()+parseInt(j(el).css('marginRight'));
			});
			// show nav w/JS to prevent display if JS disabled
			j(el0).children('.carouselNav').css({
				display: 'block',
				width: fnbWidthTotal+'px'
			});
			carouselNavUpdate(ix0);

		}

	});

	fixPngs('.carouselNavElement img');

	fixPngs('.fixPng');

});

function buttonRollover(ev) {
	if (!j(ev.target).parent('.carouselNavElement').hasClass('on')) {
		j(ev.target).parent('.carouselNavElement').stop();
		isArrow=(j(ev.target).parent('.carouselNavElement').hasClass('arrowLeft') || j(ev.target).parent('.carouselNavElement').hasClass('arrowRight'));
		j(ev.target).parent('.carouselNavElement').find('.on').animate({
			opacity: (isArrow)?1:0.5
		}, 125, 'easeInOutQuad');
	}
}
function buttonRollout(ev) {
	if (!j(ev.target).parent('.carouselNavElement').hasClass('on')) {
		j(ev.target).parent('.carouselNavElement').stop();
		j(ev.target).parent('.carouselNavElement').find('.on').animate({
			opacity: 0
		}, 125, 'easeInOutQuad');
	}
}
function boxClick(ev,ix0) {
    if (carousels[ix0].animType=='swipe') {
	clickTab(ev);
    }
    doPanelSwitch(ix0,j(ev.currentTarget).attr('ix'),true);
}
function arrowLeftClick(ev,ix0) {
	temp=carousels[ix0].cPanel-1;
	if (temp<0) {
		temp=carousels[ix0].numPanels-1;
	}
	doPanelSwitch(ix0,temp,true);
}
function arrowRightClick(ev,ix0) {
	temp=carousels[ix0].cPanel+1;
	if (temp>carousels[ix0].numPanels-1) {
		temp=0;
	}
	doPanelSwitch(ix0,temp,true);
}

function doPanelSwitch(whichCarousel,whichPanel,userClicked,init) {
     if (!carousels[whichCarousel].isAnimating) {
		clearTimeout(carousels[whichCarousel].rotateTimer);
		if (userClicked) {
			//     if (typeof(HomepageClickTracking)=='function') {
			//	if (whichDir==1) {
			//	     HomepageClickTracking('Right');
			//	} else if (whichDir==-1) {
			//	     HomepageClickTracking('Left');
			//	}
			//     }
			//     if (typeof(console)!='undefined') {
			//	if (typeof(console.log)=='function') {
			//	     if (whichDir==1) {
			//		console.log('HP TRACKING: '+'Right');
			//	     } else if (whichDir==-1) {
			//		console.log('HP TRACKING: '+'Left');
			//	     }
			//	}
			//     }
		}
		carousels[whichCarousel].isAnimating=true;
		var oldPanel=carousels[whichCarousel].cPanel;
		if (whichPanel<0) {
			carousels[whichCarousel].cPanel++;
		} else {
			carousels[whichCarousel].cPanel=whichPanel;
		}
		if (carousels[whichCarousel].cPanel>carousels[whichCarousel].numPanels-1) {
			carousels[whichCarousel].cPanel=0;
		}
		if (carousels[whichCarousel].cPanel<0) {
			carousels[whichCarousel].cPanel=carousels[whichCarousel].numPanels-1;
		}

		switch(carousels[whichCarousel].animType) {
			case 'swipe':
			    //not handled by this script, see "updateScrollArea" which runs on an interval
			    carousels[whichCarousel].isAnimating=false;
			break;
			case 'slide':
				//get whether panel should move left or right
				if (oldPanel<carousels[whichCarousel].cPanel) {
					dirString='-';
				} else {
					dirString='';
				}
				// reposition all panels at 0
				j(carousels[whichCarousel].element).find('.panel').each(function(ix,el) {
					j(el).css({
						zIndex: (init)?66:67,
						display: (ix==carousels[whichCarousel].cPanel || ix==oldPanel) ? 'block' : 'none',
						left: '0px'
					});
				});
				// shuffle stack
				j(carousels[whichCarousel].panels[carousels[whichCarousel].cPanel]).css({
					zIndex: (init)?67:66
				});
				// slide out old feature
				j(carousels[whichCarousel].panels[oldPanel]).animate({
					left: dirString+j(carousels[whichCarousel].element).width()+'px'
				}, carousels[whichCarousel].animTime, 'easeInOutQuad', function() {
					carousels[whichCarousel].isAnimating=false;
					j(carousels[whichCarousel].panels[oldPanel]).css({ display: 'none' });
				});
			break;
			case 'fullslide':
				// slide entire group to show correct one
				if (!userClicked && carousels[whichCarousel].cPanel==0) {
					// different animation if on last panel in automatic advance mode
					j(carousels[whichCarousel].panels).each(function(ix,el) {
						// move first panel right of last one
						if (ix==0) {
							j(el).css({
								left: carousels[whichCarousel].width+'px'
							});
						}
						j(el).animate({
							left: '-='+carousels[whichCarousel].width+'px'
						}, carousels[whichCarousel].animTime, 'easeInOutQuad', function() {
							carousels[whichCarousel].isAnimating=false;
							// reset all panels for regular animation next time
							j(carousels[whichCarousel].panels).each(function(ix,el) {
								j(el).css({ left: (ix*carousels[whichCarousel].width)+'px' });
							});
						});
					});
				} else {
					distance=Math.abs(carousels[whichCarousel].cPanel-oldPanel);
					j(carousels[whichCarousel].panels).each(function(ix,el) {
						offset=ix-carousels[whichCarousel].cPanel;
						j(el).animate({
							left: (offset*j(carousels[whichCarousel].element).width())+'px'
						}, carousels[whichCarousel].animTime*distance, 'easeInOutQuad', function() {
							carousels[whichCarousel].isAnimating=false;
						});
					});
				}
			break;
			case 'crossfade':
				// make new feature transparent
				j(carousels[whichCarousel].element).find('.panel').each(function(ix,el) {
					j(el).css({
						zIndex: 66,
						display: (ix==carousels[whichCarousel].cPanel || ix==oldPanel) ? 'block' : 'none',
						opacity: (ix==oldPanel || (init && ix==0)) ? 1 : 0
					});
				});
				// shuffle stack
				j(carousels[whichCarousel].panels[carousels[whichCarousel].cPanel]).css({
					zIndex: 67
				});
				// fade in new feature
				j(carousels[whichCarousel].panels[carousels[whichCarousel].cPanel]).animate({
					opacity: 1
				}, carousels[whichCarousel].animTime, 'easeInOutQuad', function() {
					carousels[whichCarousel].isAnimating=false;
					j(carousels[whichCarousel].panels[oldPanel]).css({ display: 'none' });
				});
			break;
			case 'fade':
			default:
				// update fadeCover to cover oldPanel
				if (!init) { // if init, do nothing but set isAnimating back to false
					j(carousels[whichCarousel].element).find('.fadeCover').css({
						display: 'block',
						opacity: 0,
						width: j(carousels[whichCarousel].panels[carousels[whichCarousel].oldPanel]).width()+'px',
						height: j(carousels[whichCarousel].panels[carousels[whichCarousel].oldPanel]).height()+'px'
					});
					// animate cover in
					j(carousels[whichCarousel].element).find('.fadeCover').animate({
						opacity: 1
					}, carousels[whichCarousel].animTime, 'easeInOutQuad', function() {
						// swap, then animate cover out
						j(carousels[whichCarousel].element).find('.fadeCover').css({
							width: j(carousels[whichCarousel].panels[carousels[whichCarousel].cPanel]).width()+'px',
							height: j(carousels[whichCarousel].panels[carousels[whichCarousel].cPanel]).height()+'px'
						});
						j(carousels[whichCarousel].element).find('.panel').each(function(ix,el) {
							j(el).css({
							zIndex: 66,
							display: (ix==carousels[whichCarousel].cPanel) ? 'block' : 'none'
							});
						});
						j(carousels[whichCarousel].element).find('.fadeCover').animate({
							opacity: 0
						}, carousels[whichCarousel].animTime, 'easeInOutQuad', function() {
							carousels[whichCarousel].isAnimating=false;
							j(carousels[whichCarousel].element).find('.fadeCover').css({ display: 'none' });
						});
					});
				} else {
					carousels[whichCarousel].isAnimating=false;
				}
		}

		carouselNavUpdate(whichCarousel);

     }
}

function carouselNavUpdate(whichCarousel) {
     // feature nav update
	switch (carousels[whichCarousel].navType) {
		case 'count':
			//update display "# of #" only, buttons never need updating in this mode
			temp=j(carousels[whichCarousel].element).attr('oftext');
			temp=temp.replace('[1]',carousels[whichCarousel].cPanel+1);
			temp=temp.replace('[2]',carousels[whichCarousel].numPanels);
			j(carousels[whichCarousel].element).find('.stateIndicator').html(temp);
		break;
		case 'boxes':
		default:
			j(carousels[whichCarousel].element).find('.carouselNavElement').each(function(ix,el) {
				j(el).find('.on').stop();
				if (ix==carousels[whichCarousel].cPanel) {
					j(el).removeClass('off');
					j(el).addClass('on');
					j(el).find('.on').css({
						opacity: 1
					});
				} else {
					j(el).removeClass('on');
					j(el).addClass('off');
					j(el).find('.on').css({
						opacity: 0
					});
				}
			});
	}

        /* SPECIAL CASE HANDLING FOR NEWS/EVENTS CAROUSEL ONLY, shows/hides "all" link as needed */
        if (j(carousels[whichCarousel].element).attr('id')=='smallFeature') {
            if (j(carousels[whichCarousel].panels[carousels[whichCarousel].cPanel]).hasClass('event')) {
                j(carousels[whichCarousel].element).find('.viewAllLink.news').css('display','none');
                j(carousels[whichCarousel].element).find('.viewAllLink.event').css('display','block');
            } else {
                j(carousels[whichCarousel].element).find('.viewAllLink.news').css('display','block');
                j(carousels[whichCarousel].element).find('.viewAllLink.event').css('display','none');
            }
        }

}

// autorotate
function rotate(whichCarousel,skipAction) {
    //console.log(whichCarousel);
    if (carousels[whichCarousel].rotateDelay!=0) {
	if (skipAction!=true) {
	    if (carousels[whichCarousel].animType=='swipe') {
		clickTab();
	    } else {
		doPanelSwitch(whichCarousel,-1,false);
	    }
	}
	carousels[whichCarousel].rotateTimer=setTimeout(function() { rotate(whichCarousel); }, carousels[whichCarousel].rotateDelay);
    }
}


/* HOMEPAGE MULTIPLE-CONTENT BOXES */

var refreshContent=false;

j('.multipleContent').children('.first').css({ display: 'none' }); // if js present, override CSS showing "first" one so it doesn't flash briefly
j(document).ready(function(ev) {

	//compare cookied last load time against page modified time, if modified time is newer force display of first promos, otherwise rotate based on cookie
	if (readCookie('lastLoadTime')!=null) {
		refreshContent=mTime>Number(readCookie('lastLoadTime'));
	}
	now=new Date();
	cTime=now.getFullYear()+pad(now.getMonth()+1)+pad(now.getDate())+pad(now.getHours())+pad(now.getMinutes())+pad(now.getSeconds());
	createCookie('lastLoadTime',cTime,7);

	j('.multipleContent').each(function(ix,el) {
		hprfIdx=readCookie('hprfi'+ix);
		if (refreshContent || hprfIdx==null || isNaN(hprfIdx) || hprfIdx<0 || hprfIdx>=j(el).children('.content').length) {
			hprfIdx=0;
		}
		contents=j(el).children('.content');
		rand=getRandom(0,contents.length-1);
		contents.removeClass('first');
		contents[hprfIdx].style.display='block';
		hprfIdx++;
		createCookie('hprfi'+ix,hprfIdx,7);
	});

});

function pad(inVal) {
    if (inVal<10) {
        inVal='0'+inVal;
    }
    return inVal;
}


/* iOS-style scrolling area */
var isIOS=(window.location.search=='?forceswipe' || navigator.userAgent.match(/like Mac OS X/i));

var cVel=0;
var isDragging=false;
var isAdrag=false;
var dragTimer;
var clickTimer;
var clickTime=0;
var startMouseX;
var cMouseX;
var initialObjX;
var lastObjX=0;

var snapTo=true;
var cSnap=0;
var targetX=0;

var endReturnSpeed=0.9; // 0-1, lower is faster
var decelSpeed=0.98; // 0-1, lower is faster
var snapSpeed=0.25; // 0-1, lower is SLOWER
var snapDist=7;

var frameRate=60;

var swipeLength=350; //ms
var dragLength=100; //ms
var isSwipe;
var swipeCounter;

var maxDist=60;

var iOSareaContent;
var iOSareaMask;

var autoRotateModifier=1;

function clickTab(ev) {
    if (ev==undefined) {
	//autorotate
	cSnap++;
	if (cSnap>carousels[0].numPanels) {
	    cSnap=1;
	//    autoRotateModifier=0.25;
	//} else {
	//    autoRotateModifier=0.5;
	}
	autoRotateModifier=0.5;
    } else {
	var evEl=j(ev.target).closest('.box');
	cSnap=Number(j(evEl).attr('ix'))+1;
    }
    carousels[0].cPanel=cSnap-1;
    moveTab(cSnap);
    targetX=Math.floor((getSnapToX(0,cSnap)*-j(iOSareaContent).width())+(j(iOSareaMask).width()/2));
    targetX=Math.min(targetX,0);
    targetX=Math.max(targetX,-(j(iOSareaContent).width()-j(iOSareaMask).width()));
}

function getSnapToX(whichCarousel,which) {
    var evEl=carousels[whichCarousel].panels[which-1];
    var xPos=j(evEl).position().left+(j(evEl).width()/2);
    return xPos/j(iOSareaContent).width();
}

function moveTab(which) {
	carouselNavUpdate(0);
//    var evEl=j('.iOSareaTab')[which-1];
//    j(evEl).removeClass('iOSareaTabOver');
//    j(evEl).addClass('iOSareaTabOn');
//    j(evEl).siblings('.iOSareaTab').removeClass('iOSareaTabOn').removeClass('iOSareaTabOver');
//    var pos=Math.round(j(evEl).position().left+(j(evEl).width()/2)-17);
//    j('#iOSareaTabMarker').stop().animate({
//	left: pos+'px',
//	framerate: 30
//    },500,'easeOutQuad');
}

function setTargetX() {
    targetX=Math.floor((getSnapToX(0,cSnap)*-j(iOSareaContent).width())+(j(iOSareaMask).width()/2));
    targetX=Math.min(targetX,0);
    targetX=Math.max(targetX,-(j(iOSareaContent).width()-j(iOSareaMask).width()));
}

//next 2 funcs for integration with regular nav
function beginDrag(ev) {
    // SPECIAL CASE: replace click functionality on "overlayLink" elements contained within scroller to bypass preventDefault cancelling overlay opening
    if (j(ev.target).closest('.overlayLink').html()!=null) {
	openOverlay(j(ev.target).closest('.overlayLink').attr('overlay')); 
    } else {
	clearTimeout(carousels[0].rotateTimer);
	autoRotateModifier=1;
	startDrag(ev);
	j(ev.target).bind("click.prevent", function(ev) { ev.preventDefault(); });
	clearTimeout(clickTimer);
	isAdrag=false;
	clickTimer=setTimeout(isDrag,dragLength);
	j(ev.target).click();
    }
    ev.preventDefault(); // prevent page dragging on iOS
    return false;
}
function endDrag(ev) {
    if (!overlayIsOpen) {
	clearTimeout(carousels[0].rotateTimer);
	carousels[0].rotateTimer=setTimeout(function() {
		rotate(0);
	}, carousels[0].rotateDelay);
	//if (isAdrag || Math.abs(startMouseX-cMouseX)>10) {
	    setTimeout(function(){j(ev.target).unbind("click.prevent");}, 300);
	//} else {
	    //j(ev.target).unbind("click.prevent");
	//}
    }
    stopDrag(ev);
}

function isntSwipe() {
    isSwipe=false;
}
function isDrag() {
    isAdrag=true;
}

function startDrag(ev) {
    isDragging=true;
    cVel=0;
    var thisEl=j(ev.target).closest('.carousel')[0];
    startMouseX = mouseX(ev) - thisEl.offsetLeft;
    cMouseX = startMouseX;
    initialObjX=j(iOSareaContent).position().left;
    lastObjX=initialObjX;
    clearTimeout(swipeCounter);
    isSwipe=true;
    swipeCounter=setTimeout(isntSwipe,swipeLength);
}
function stopDrag(ev) {
    var cW=j(iOSareaContent).width();
    var minX=(j(iOSareaContent).width()-j(iOSareaMask).width());
    //if ((j(ev.target).closest('.screenshotThumb').html())!=null && (Math.abs(startMouseX-cMouseX)<=10 || cMouseX=='undefined')) {
    //    openOverlay(j(ev.target).closest('.overlayLinkSpecial').attr('overlay'));
    //}
    if (isDragging) {
	clearTimeout(swipeCounter);
	if (snapTo && isSwipe) {
	    isSwipe=false;
            if (Math.abs(startMouseX-cMouseX)>10 && cMouseX!='undefined') { // prevent swipe on click
                if (startMouseX<=cMouseX) { //right
                    cSnap=Math.max(cSnap-1,1);
                } else { //left
                    cSnap=Math.min(cSnap+1,j(iOSareaContent).find('.panel').length);
                }
		carousels[0].cPanel=cSnap-1;
                moveTab(cSnap);
                setTargetX();
            }
	} else {
	    if (snapTo) {
		cVel=0;
		targetX=0;
		var centerX=-j(iOSareaContent).position().left+(j(iOSareaMask).width()/2);
		var leftXperc=centerX/j(iOSareaContent).width();
		cSnap=1;
		for (i=1;i<j(iOSareaContent).find('.panel').length;i++) {
		    if (leftXperc>getSnapToX(0,i)) {
			cSnap=i;
		    }
		}
		if (leftXperc-getSnapToX(0,cSnap)>(getSnapToX(0,cSnap+1)-getSnapToX(0,cSnap))/2) {
		    cSnap++;
		}
		carousels[0].cPanel=cSnap-1;
		moveTab(cSnap);
                setTargetX();
	    } else {
		if (cVel>0) {
		    cVel=Math.max(10,Math.min(cVel,100));
		} else if (cVel<0) {
		    cVel=Math.min(-10,Math.max(cVel,-100));
		}
	    }
	}
	isDragging=false;
    }
    if (isAdrag || Math.abs(startMouseX-cMouseX)>10) {
	ev.preventDefault();
	return false;
    } else {
	var clickedEl=j(ev.target).closest('a')[0];
	if (clickedEl!=undefined) {
	    if (j(clickedEl).attr('href')!='' && j(clickedEl).attr('href')!=undefined && j(clickedEl).attr('href')!='#') {
		if (j(clickedEl).attr('target')!='') {
		    window.open(j(clickedEl).attr('href'),j(clickedEl).attr('target'));
		} else {
		    window.location.href=j(clickedEl).attr('href');
		}
	    } else {
		j(clickedEl).click();
	    }
	}
    }    
}

function mouseX(evt) {
    var val;
    if (navigator.userAgent.match(/like Mac OS X/i)) {
	val = evt.originalEvent.touches[0].pageX;
    } else {
	if (!evt) { evt = window.event; }
	if (evt.pageX) {
	    val = evt.pageX;
	} else if (evt.clientX) {
	    val = evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	} else {
	    val = 0;
	}
    }
    return val;
}

function updatePos(ev) {
    var thisEl=j(iOSareaMask)[0];
    cMouseX=mouseX(ev) - thisEl.offsetLeft;
    if (isDragging) {
	var newX=(initialObjX+cMouseX-startMouseX);
	j(iOSareaContent).css('left',newX+'px');
    }
}
function updateScrollArea() {
    var cX=j(iOSareaContent).position().left;
    var cW=j(iOSareaContent).width();
    var minX=(cW-j(iOSareaMask).width());
    if (isDragging) {
	cVel=(cX-lastObjX);
	lastObjX=cX;
    } else {
	if (snapTo) {
	    if (cX!=targetX) {
		if (Math.abs(cX-targetX)>snapDist) {
		    var dist=((targetX-cX)*(snapSpeed*autoRotateModifier));
		    if (dist!=0 && Math.abs(dist)<(snapDist*autoRotateModifier)) {
			if (dist>0) {dist=(snapDist*autoRotateModifier);}
			if (dist<0) {dist=-(snapDist*autoRotateModifier);}
		    }
		    if (dist!=0 && Math.abs(dist)>maxDist) {
			if (dist>0) {dist=(maxDist*autoRotateModifier);}
			if (dist<0) {dist=-(maxDist*autoRotateModifier);}
		    }
		    cX=cX+dist;
		} else {
		    cX=targetX;
		}
		j(iOSareaContent).css('left',Math.round(cX)+'px');
	    }
	} else { // coast
	    if (cX>0) {
		cVel=0;
		cX*=endReturnSpeed;
		j(iOSareaContent).css('left',Math.floor(cX)+'px');
	    } else if (cX<-minX) {
		cVel=0;
		cX=-minX+((cX+minX)*endReturnSpeed);
		j(iOSareaContent).css('left',Math.floor(cX)+'px');
	    } else {
		cVel*=decelSpeed;
		if (cVel<1 && cVel>-1) { cVel=0; }
		if (cVel!=0) {
		    j(iOSareaContent).css('left',(j(iOSareaContent).position().left+Math.floor(cVel))+'px');
		}
	    }
	}
    }
}
