/*
 * Special event for image load events
 * Needed because some browsers does not trigger the event on cached images.

 * MIT License
 * Paul Irish     | @paul_irish | www.paulirish.com
 * Andree Hansson | @peolanha   | www.andreehansson.se
 * 2010.
 *
 * Usage:
 * $(images).bind('load', function (e) {
 *   // Do stuff on load
 * });
 * 
 * Note that you can bind the 'error' event on data uri images, this will trigger when
 * data uri images isn't supported.
 * 
 * Tested in:
 * FF 3+
 * IE 6-8
 * Chromium 5-6
 * Opera 9-10
 */
(function ($) {
	$.event.special.load = {
		add: function (hollaback) {
			if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
				// Image is already complete, fire the hollaback (fixes browser issues were cached
				// images isn't triggering the load event)
				if ( this.complete || this.readyState === 4 ) {
					hollaback.handler.apply(this);
				}

				// Check if data URI images is supported, fire 'error' event if not
				else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
					$(this).trigger('error');
				}
				
				else {
					$(this).bind('load', hollaback.handler);
				}
			}
		}
	};
}(jQuery));



// jQuery.support.transition
// to verify that CSS3 transition is supported (or any of its browser-specific implementations)
$.support.transition = (function(){ 
    var thisBody = document.body || document.documentElement,
    thisStyle = thisBody.style,
    support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined;
    
    return support; 
})();


/*
 * jSwipe - jQuery Plugin
 * http://plugins.jquery.com/project/swipe
 * http://www.ryanscherf.com/demos/swipe/
 *
 * Copyright (c) 2009 Ryan Scherf (www.ryanscherf.com)
 * Licensed under the MIT license
 *
 * $Date: 2009-07-14 (Tue, 14 Jul 2009) $
 * $version: 0.1.2
 * 
 * This jQuery plugin will only run on devices running Mobile Safari
 * on iPhone or iPod Touch devices running iPhone OS 2.0 or later. 
 * http://developer.apple.com/iphone/library/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW5
 */
(function($) {
	$.fn.swipe = function(options) {
		
		// Default thresholds & swipe functions
		var defaults = {
			threshold: {
				x: 30,
				y: 10
			},
			swipeLeft: function() { alert('swiped left') },
			swipeRight: function() { alert('swiped right') }
		};
		
		var options = $.extend(defaults, options);
		
		if (!this) return false;
		
		return this.each(function() {
			
			var me = $(this)
			
			// Private variables for each element
			var originalCoord = { x: 0, y: 0 }
			var finalCoord = { x: 0, y: 0 }
			
			// Screen touched, store the original coordinate
			function touchStart(event) {
				//console.log('Starting swipe gesture...')
				originalCoord.x = event.targetTouches[0].pageX
				originalCoord.y = event.targetTouches[0].pageY
			}
			
			// Store coordinates as finger is swiping
			function touchMove(event) {
			    event.preventDefault();
				finalCoord.x = event.targetTouches[0].pageX // Updated X,Y coordinates
				finalCoord.y = event.targetTouches[0].pageY
			}
			
			// Done Swiping
			// Swipe should only be on X axis, ignore if swipe on Y axis
			// Calculate if the swipe was left or right
			function touchEnd(event) {
				//console.log('Ending swipe gesture...')
				var changeY = originalCoord.y - finalCoord.y
				if(changeY < defaults.threshold.y && changeY > (defaults.threshold.y*-1)) {
					changeX = originalCoord.x - finalCoord.x
					
					if(changeX > defaults.threshold.x) {
						defaults.swipeLeft()
					}
					if(changeX < (defaults.threshold.x*-1)) {
						defaults.swipeRight()
					}
				}
			}
			
			// Swipe was started
			function touchStart(event) {
				//console.log('Starting swipe gesture...')
				originalCoord.x = event.targetTouches[0].pageX
				originalCoord.y = event.targetTouches[0].pageY
				
				finalCoord.x = originalCoord.x
				finalCoord.y = originalCoord.y
			}
			
			// Swipe was canceled
			function touchCancel(event) { 
				//console.log('Canceling swipe gesture...')
			}
			
			// Add gestures to all swipable areas
			this.addEventListener("touchstart", touchStart, false);
			this.addEventListener("touchmove", touchMove, false);
			this.addEventListener("touchend", touchEnd, false);
			this.addEventListener("touchcancel", touchCancel, false);
				
		});
	};
})(jQuery);


// ====================
// = itunes detection =
// ====================

var _detect;
(function($){
	_detect = {
	    activeX: function(){
	        // проверяем наличие iTunes через ActiveX (актуально только для IE)
	        var b = document.getElementById("iTunesDetectorIE");
	        var a = false;
	        if ((b != null) && (typeof(b) != "undefined")) {
	            if (typeof(b.IsITMSHandlerAvailable) != "undefined") {
	                a = b.IsITMSHandlerAvailable;
	            }
	            if ((a == null) || (typeof(a) == "undefined")) {
	                a = false
	            }
	        }
	        return a
	    },
	    plugin: function(){
	        // проверяем наличие установки через navigator.plugins (актуально для всех браузеров, кроме IE)
	        var a = false;
	        if (navigator.plugins && navigator.plugins.length > 0) {
	            for (var b = 0; b < navigator.plugins.length; b++) {
	                var c = navigator.plugins[b];
	                var d = c.name;
	                if (d.indexOf("iTunes Application Detector") > -1) {
	                    a = true
	                }
	            }
	        }
	        return a
	    },
	    iTunes: function(){
	        return ((navigator.userAgent.indexOf("Macintosh") != -1) // если Macintosh – iTunes стоит
	            || (!_detect.isIE() && _detect.plugin()) // смотрим в navigator.plugins
	            || (_detect.isIE() && _detect.activeX()) // смотрим через ActiveX в IE
	            || false);
	    },
	    isIE: function() {
	       return '\v' == 'v';
	    }
	};
})(jQuery);


// ================
// = YINZCAM CODE =
// ================

$(function(){
	
	// =======================================================
	// =                     SLIDESHOW                       =
	// =======================================================
	
	var animated;
	var transition_duration = 1*1000;
	var cur_index;//note: slides start at 1. (slide 0 is the empty stage)
	var prev;//$(items[0]);//the item that comes with an active state
	
	if(!$.support.transition){
		cur_index = 1;
		set_active_btn($('.carousel .menu .item')[0]);
	}
	var stage_pos = 0;
	var slide_width = 0
	function gotoSlide(index){
		//console.log('goto slide: '+index);
		if(!animated){

			if(true){
			//if( $.support.transition ){
				//console.log('supports ntive css transition');
				//native css transition
				slide_width = $('.carousel .slideshow .slide').width();
				//console.log('slide width: '+slide_width);
				stage_pos = -slide_width*(index-1);
				var transform = 'translateX('+stage_pos+'px)';
				$('.carousel .slideshow .stage').css({
					'-moz-transform':transform,
					'-webkit-transform':transform
				});
				setTimeout(function(){
					animated = false;
				},transition_duration);
			}else{
				//console.log('browser does not support css3 transition');
				animated = true;
				slide_width = $('.carousel .slideshow .slide').width();
				stage_pos = -slide_width*(index-1);
				$('.carousel .slideshow .stage').animate({left:(stage_pos)+'px'},1000,'swing',function(){
					animated = false;
				});
			}
			
			set_active_btn($('.carousel .menu .item')[index-1]);
			
			//reset the 'next-slide' timer
			cur_index = index;
			clearInterval(interval);
			interval = setInterval(gotoNextSlide,5000);
			
			var new_btn = $('.carousel .menu .item')[index-1];
			$(new_btn).addClass('active');
			if(prev!==new_btn){
				$(prev).removeClass('active');
				prev = new_btn;
			}
			
			return true;
		}
		return false;
	}
	
	function set_active_btn(btn){
		$(btn).addClass('active');
		if(prev!==btn){
			$(prev).removeClass('active');
			prev = btn;
		}
	}
	
	function gotoNextSlide(){
		var new_index = cur_index + 1;
		var num_slides = $('.carousel .slideshow .slide').length;
		if( new_index > num_slides )
			new_index = 1;
		gotoSlide(new_index);
	}
	
	function goRight(){
		var new_index = cur_index - 1;
		if( new_index > 0 ){
			gotoSlide(new_index);
		}
	}
	
	function goLeft(){
		var new_index = cur_index + 1;
		if( new_index - 1 < $('.carousel .slideshow .slide').length ){
			gotoSlide(new_index);
		}
	}
	

	//console.log(items);
	
	function setup_slideshow_events(){
		prev = null;
		cur_index = 0;
		animated = false;
		// $.each($('.carousel .slideshow .slide'),function(index,item){
		// 	$(item).click(function(){
		// 		gotoSlide(index+1);
		// 	});
		// });
		$('.carousel .arrow-left').click(goRight);
		$('.carousel .arrow-right').click(goLeft);
	}
	
	setup_slideshow_events();
	
	//detect swipe event on touch devices
	//$('.carousel .slideshow .stage').swipe( { swipeLeft: goRight , swipeRight: goLeft } );
	
	var interval;
	setTimeout(function(){
		interval = setInterval(gotoNextSlide,5000);
		gotoNextSlide(1);
	},1000);
	
	// ====================
	// = itunes detection =
	// ====================
	var color_box_links;
	function replace_app_links_for_device(){
		var link_type;
		var is_mobile = false;
		//console.log('before');
		//console.log(navigator.userAgent);
		if( navigator.userAgent.match(/Android/i) ){
			//do stuff for android device
			//console.log('android device');
			link_type = "android";
			is_mobile = true;
		}else if( navigator.userAgent.match(/BlackBerry/i) ){
			//blackberry device
			//console.log('black berry device');
			link_type = "bb";
			is_mobile = true;
		}else if( 
			navigator.userAgent.match(/iPhone/i) ||
			navigator.userAgent.match(/iPod/i) ||
			navigator.userAgent.match(/iPad/i)
		){
			// iOS device
			//console.log('iOS device');
			link_type = "ios";
			is_mobile = true;
		}else{
			//probably not a handset. try and detect support for itunes
			if( _detect.iTunes() && !navigator.userAgent.match(/Chrome/i) ){
				// it's not a known mobile device but it has the itunes plugin so open the app page for itunes
				//console.log('itunes browser');
				link_type = "ios";
			}else{
				link_type = null;//leave the links untouched
			}
		}
	}
	replace_app_links_for_device();
	
	var is_cb_open = false;
	$(document).bind('cbox_complete',function(){
		is_cb_open = true;
	});
	$(document).bind('cbox_closed',function(){
		is_cb_open = false;
	});
});
