(function () {
	var old_orientation = window.orientation;
	var $modal = $('<ul class="modal"></ul>');
	var $start_modal = $('<p class="modal-start">Work</p>');
	$modal.overlay = $('<div id="overlay"></div>');
	$modal.overlay.appendTo('.body');
	$modal.openModal = function () {
		$modal.find('a').removeClass('active');
		$modal.overlay.fadeIn(100, function () {
			$modal.fadeIn(300);
		});
	}
	$modal.closeModal = function () {
		$modal.fadeOut(300, function () {
			$modal.overlay.hide();
		});
	}

	function get_orientation() {
		var orient = "landscape";

		if (window.orientation == 0 || window.orientation == 180) {
			orient = "portrait";
		}

		return orient;
	}

	function isIPad() {
		return navigator.platform == "iPad";
	}

	//build client slider
	$('.slider-wrapper').each(function () {
		var $wrapper = $(this);
		var $ul = $wrapper.find('ul');
		var $chapters_ul = $('<ul class="chapters"></ul>');
		var orientation = get_orientation();
		var current_index = 0;
		var $status = $('.status');

		$.get('slide-show/slide-show.txt', function (data) {
			var csv = jQuery.csv(",", "\"", "\r\n\|")(data);
			//generate chapter and images list
			var chapters = [];
			var chapter = [];
			var active_chapter = [];
			var links_prev = [];
			var links_next = [];
			//images array is containing all items, videos and images
			var images = [];
			//array storing info if item is video
			var item_is_video = [];
			//store players to access them easily
			var players = [];
			var images_chapters = [];
			var chapter_anchor_slides = [];

			$.each(csv, function (index) {
				//only images for this client
				if (index > 0 && csv[index][1] == client_name && csv[index][0] != '') {
					var is_video = csv[index][0].endsWith('.mp4');
					var is_html = csv[index][0].endsWith('html');
					if (is_video) {
						csv[index][0] = csv[index][0].substring(0, csv[index][0].length - 4);
					}
					item_is_video.push(is_video);
					chapter = [csv[index][2], csv[index][0], index];

					links_prev.push(csv[index][3]);
					links_next.push(csv[index][4]);

					images.push(csv[index][0]);
					images_chapters.push(csv[index][2]);

					if (!active_chapter.length || active_chapter[0] != chapter[0]) {
						active_chapter = chapter;
						chapters.push(chapter);
					}

					var tmp = null;

					var appstoreLink = csv[index][5];
					if (appstoreLink) {
						appstoreLink = '<a class="appstore" target="_blank" href="' + appstoreLink + '">App Store</a>';
					} else {
						appstoreLink = "";
					}

					if (is_video) {
						var vidHeight = 480;
						var vidWidth = 640;
						var wideClass = "";
						if (csv[index][6] == 'wide') {
							if (get_orientation() == "portrait") {
								vidHeight = 270;
								vidWidth = 480;
							} else {
								vidHeight = 480;
								vidWidth = 852;
							}
		
							wideClass = 'video-wide';
						}
						$ul.append('<li><div class="video-container ' + wideClass + ' wrap-' +  csv[index][0] +'"><div id="vid-' + csv[index][0] + '"></div></div>' + appstoreLink + '</li>');
								console.log(vidWidth + "    " + csv[index][0]);
						$('.video-wide.wrap-' +  csv[index][0]).css({ width: vidWidth + 'px', height: vidHeight + 'px' });
						tmp = jwplayer("vid-" + csv[index][0]).setup({
							file: "slide-show/" + csv[index][0] + ".mp4",
							height: vidHeight,
							width: vidWidth,
							image: 'slide-show/' + csv[index][0] + '.png',
							stretching: 'exactfit',
							players: [
                                { type: "flash", src: "scripts/player.swf" },
                                { type: "html5" }
                            ]
						});
					} else if (is_html) {
						$ul.append('<li><div id="html-block-' + csv[index][0] + '"></div></li>');
						$.get('slide-show/' + csv[index][0].replace('-html', '.html'), function (data) {
							$('#html-block-' + csv[index][0]).html(data);
						});
					} else {
						$ul.append('<li><img src="slide-show/' + csv[index][0] + '_' + orientation + '.jpg" alt=""/>' + appstoreLink + '</li>');
					}
					players.push(tmp);
				}
			});
			//append chapters list
			$.each(chapters, function (index) {
				chapter_anchor_slides.push([chapters[index][1], chapters[index][2]]);
				$chapters_ul.append('<li><a href="#' + chapters[index][1] + '">&gt; ' + chapters[index][0] + '</a></li>');
			});
			$chapters_ul.insertAfter('ul.slider .intro i');

			//sliding code
			var $container = $wrapper;
			var $slider = $container;
			var $list = $ul;
			var $items = $list.find('li');
			var item_width = $items.width();
			var speed = isIPad() ? 500 : 700;
			var new_margin = 0;

			$slider.is_video_on_slide = function () {
				return item_is_video[current_index - 1];
			};

			$slider.updateStatus = function () {
				var current_anchor = "";
				$.each(chapter_anchor_slides, function (index, anchor_slide) {
					if ((anchor_slide[1] - chapter_anchor_slides[0][1] + 1) <= current_index) {
						current_anchor = anchor_slide[0];
					}

				});
				$status.find('i').html('<a href="#' + current_anchor + '" >' + images_chapters[current_index - 1] + '</a>');
				if (current_index == 0 && location.hash != '') {
					location.hash = '';
				} else {
					location.hash = images[current_index - 1] ? images[current_index - 1] : '';
				}

				$('.status').find('i').find('a').click(function () {
					$slider.fromHash($(this).hrefId());
				});

				//show/hide prev/next links on first last element
				if (current_index == 0) {
					$wrapper.find('a.prev').hide();
					$status.hide();
				} else {
					$wrapper.find('a.prev').show();
					$status.show();
				}

				//show / hide active are modal-start
				if ($slider.is_video_on_slide()) {
					$start_modal.css('z-index', 0);
				} else {
					$start_modal.css('z-index', 9997);
				}
			};

			$slider.fromHash = function (hash) {
				var selected_image = 'slide-show/' + hash + '_' + get_orientation() + '.jpg';
				var $html_block = $ul.find('#html-block-' + hash);

				var $image = ($html_block.length) ? $html_block : $ul.find('img[src$="' + selected_image + '"]');
				if ($image.length) {
					current_index = $ul.find('li').index($image.parent()) - chapters.length;
					//$wrapper.scrollList(current_index);
					$list.stop(true).css({ 'margin-left': -1 * current_index * item_width + 'px' });
					$slider.updateStatus();
				} else {
					//since we added posibility to embed video, we have to check if video item with specified id is present
					var $video = $ul.find('#vid-' + hash);
					if ($video.length) {
						current_index = $ul.find('li').index($video.parent().parent()) - chapters.length;
						//$wrapper.scrollList(current_index);
						$list.stop(true).css({ 'margin-left': -1 * current_index * item_width + 'px' });
						$slider.updateStatus();
					}

				}
			};


			$slider.scrollList = function (index) {
				//check prev and next index for video players and stop them
				var prev_video = index >= 2 ? players[index - 2] : null;
				var next_video = players[index];

				if (prev_video) {
					prev_video.stop();
				}
				if (next_video) {
					next_video.stop();
				}

				new_margin = -1 * index * item_width;

				$list.stop(true).animate({ 'margin-left': new_margin + 'px' }, speed, isIPad() ? 'linear' : 'swing', function () {
					$slider.updateStatus();
				});
			}
			$list.css({ width: item_width * $items.length });

			// chapters links
			$chapters_ul.find('a').click(function () {
				$slider.fromHash($(this).hrefId());
			});

			//add prev and next links to page
			$wrapper.append('<a href="#" class="prev" title="Previous">Prev</a>');
			$wrapper.append('<a href="#" class="next" title="Next">Next</a>');
			$wrapper.find('a.next').show();
			$wrapper.find('a.prev, a.next').click(function (evt) {
				evt.preventDefault();
				if ($ul.is(':animated')) {
					return;
				}
				//check if there are harcoded links for this image and forward to it
				var url = $(this).hasClass('prev') ? links_prev[current_index - 1] : links_next[current_index - 1];
				if (url) {
					window.location = url + '.html';
				}
				var new_index = $(this).hasClass('prev') ? current_index - 1 : current_index + 1;
				current_index = new_index;

				if (new_index > links_next.length || new_index < 0) {
					//do nothing
					return;
				}

				$wrapper.scrollList(new_index);
			});
			//scroll to selected image
			if (location.hash) {
				$slider.fromHash(location.hash.replace('#', ''));
			}

			//change images while rotating
			$(window).bind('orientationchange', function () {
				old_orientation = window.orientation == 0 || window.orientation == 180 ? 'portrait' : 'landscape';
				var from_orient = old_orientation == 'landscape' ? 'portrait' : 'landscape';
				center_content();
				$slider.find('img').each(function () {
					$(this).attr('src', $(this).attr('src').replace('_' + from_orient, '_' + old_orientation));
					//change slider margin, calculate new dimensions
					item_width = $items.width();
					$list.css({ width: item_width * $items.length });
					$list.css({ 'margin-left': -1 * current_index * item_width + 'px' });
				});
			});
			$list.inEvent = false;
			$list.touchstart_evt = function (evt) {
				if (evt.originalEvent.targetTouches.length != 1) {
					return true;
				}
				if ($list.inEvent) {
					return true;
				}
				$list.inEvent = true;
				if (!$(evt.target).closest(".modal").length) {
					$modal.closeModal();
				}
				$slider.touchStartX = evt.originalEvent.targetTouches[0].clientX;
				$slider.touchStartY = evt.originalEvent.targetTouches[0].clientY;
				$slider.startMarginLeft = parseInt($list.css('margin-left'));

				$list.bind('touchmove', function (evt) {
					$list.touchmove_evt(evt);

					return true;
				});
				$start_modal.bind('touchmove', function (evt) {
					$list.touchmove_evt(evt);

					return true;
				});

				$list.bind('touchend', function (evt) {
					$list.touchend_evt(evt);

					return true;
				});

				$start_modal.bind('touchend', function (evt) {
					$list.touchend_evt(evt);

					return true;
				});
			};

			$list.touchmove_evt = function (evt) {
				if (evt.originalEvent.targetTouches.length != 1) {
					return true;
				}
				evt.preventDefault();
				var leftDelta = evt.originalEvent.targetTouches[0].clientX - $slider.touchStartX;
				var leftMargin = $slider.startMarginLeft + leftDelta;
				//            if (leftDelta < -50) {
				//                $wrapper.find('a.next').click();
				//            } else if (leftDelta > 50) {
				//                $wrapper.find('a.prev').click();
				//            }

				//if ((current_index == 0 && leftDelta > 0) || (current_index == images.length && leftDelta < 0)) {
				if ((current_index == 0 && leftDelta > 0)) {
					return true;
				}
				$slider.leftDelta = leftDelta;
				$slider.moveEvent = evt;
				$list.css('margin-left', leftMargin);
			};

			$list.touchend_evt = function (evt) {
				if ($slider.moveEvent && $slider.moveEvent.originalEvent.targetTouches.length != 1) {
					return true;
				}
				$list.inEvent = false;
				evt.preventDefault();
				$list.unbind('touchmove');
				$start_modal.unbind('touchmove');
				$list.unbind('touchend');
				$start_modal.unbind('touchend');
				var leftDelta = $slider.leftDelta;
				$slider.leftDelta = 0;

				if (Math.abs(leftDelta) < 100) {
					$list.animate({ 'margin-left': $slider.startMarginLeft + 'px' }, 300);
				}
				if (leftDelta < 0) {
					$wrapper.find('a.next').click();
				} else if (leftDelta > 0) {
					$wrapper.find('a.prev').click();
				}
			};

			//add touchmove ovents for ipad
			$list.bind('touchstart', function (evt) {
				$list.touchstart_evt(evt);

				return true;
			});
			$start_modal.bind('touchstart', function (evt) {
				$list.touchstart_evt(evt);

				return true;
			});


		});
	});


	//construct home slider
	$('.home-slider-wrapper').each(function () {
		var $wrapper = $(this);
		var $ul = $(' <ul class="home-slider"></ul>');
		var orientation = get_orientation();
		$.get('home-page-images/home-page-images.txt', function (data) {
			var csv = jQuery.csv(",", "\"", "\r\n\|")(data);
			$.each(csv, function (index) {
				if (csv[index].length == 4 && index > 0) {
					$ul.append('<li><img src="home-page-images/' + csv[index][0] + '_' + orientation + '.jpg" alt=""/><a href="' + csv[index][2] + '.html"><b>' + csv[index][1] + '</b> ' + csv[index][3] + '</a></li>');
				}
			});
			$ul.appendTo($wrapper);
			//home slider, fade in/out
			var $slider = $ul;
			var $container = $slider.parent();
			var $header_images = $slider.find('li');
			if ($header_images.length <= 1) return;
			var header_timeout = null;
			var header_timeout_time = 5000;
			var header_animation_time = 1500;
			var max_z_index = $header_images.length + 1;
			var active_index = Math.floor(Math.random() * $header_images.length + 1);
			var pool = [];


			$header_images.each(function (index) {
				$(this).css('z-index', $header_images.length - index);
			});
			//set random image on top
			$header_images.eq(active_index).css('z-index', $header_images.length + 1);

			//random image

			var pickImage = function () {
				if (!pool.length) {
					$header_images.each(function (index) {
						if (index != active_index)
							pool.push(index);
					});
				}
				var randomIndex = Math.floor(Math.random() * pool.length);
				var pickedIndex = pool.splice(randomIndex, 1);

				return pickedIndex;
			};

			var rotateHeadImage = function (index_to_show) {
				if (index_to_show > $header_images.length - 1) index_to_show = 0;
				active_index = index_to_show;
				$($header_images.get(index_to_show)).hide().css('z-index', (max_z_index++)).fadeIn(header_animation_time, function () {
					header_timeout = setTimeout(function () {
						rotateHeadImage(pickImage());
					}, header_timeout_time);
				});
			}

			//start switching
			header_timeout = setTimeout(function () {
				rotateHeadImage(pickImage());
			}, header_timeout_time);

			//change images while rotating
			$(window).bind('orientationchange', function () {
				old_orientation = window.orientation == 0 || window.orientation == 180 ? 'portrait' : 'landscape';
				var from_orient = old_orientation == 'landscape' ? 'portrait' : 'landscape';
				center_content();
				$header_images.find('img').each(function () {
					$(this).attr('src', $(this).attr('src').replace('_' + from_orient, '_' + old_orientation));
				});
			});
		});
	});

	//center content on the page
	var center_content = function () {
		if (isIPad()) {
			return;
		}
		var $content = $('.wrapper-top');
		var top_margin = ($(window).height() - $content.height()) / 2;
		if (top_margin < 0) return;
		$content.css('margin-top', top_margin);
	};
	center_content();

	//build modal window with client list
	$('.menu .work').each(function () {

		//load data and build list with all clients
		var data = [
                    ['01', 'Partners in Change', 'Samsung', '01_Samsung.html'],
                    ['02', 'Intelligent Expression', 'PartnerRe', '02_PartnerRe.html'],
                    ['03', 'Achieving Authority', 'MasterCard', '03_MasterCard.html'],
                    ['04', 'Ambition on Display', 'Abbott', '04_Abbott.html'],
                    ['05', 'It’s in the Details', 'Rexam', '05_Rexam.html'],
                    ['06', 'Green is Good', 'Turner', '06_Turner.html']
                ];
		$.each(data, function (index) {
			var extra = '';
			if (index == 5) {
				extra = ' class="last"';
			}
			$modal.append('<li' + extra + '><a href="' + data[index][3] + '"><i class="no">' + data[index][0] + '</i><b>' + data[index][2] + '</b><span>' + data[index][1] + '</span></a></li>');
		});
		//add click events
		$modal.find('a').click(function (e) {
			e.preventDefault();
			if (isIPad()) {
				$(this).addClass('active');
			}
			var href = $(this).attr('href');
			setTimeout(function () {
				window.location = href;
			}, 200);
		});
		//append list to page
		$modal.appendTo($('.body'));


		if (isIPad()) {
			//for ipad
			$('body').bind("touchstart", function (e) {
				if (e.originalEvent.targetTouches.length != 1) {
					return true;
				}
				if (!$(e.target).closest(".modal").length) {
					$modal.closeModal();
				}
			});
		} else {
			$("body").mousedown(function (e) {
				if (!$(e.target).closest(".modal").length) {
					$modal.closeModal();
				}
			});
		}

		//click this to open modal window

		$start_modal.click(function () {
			$('.work').click();
		});
		if (($.browser.msie && $.browser.version == '7.0') || isIPad()) {
			$start_modal.appendTo($('.body'));
		} else {
			$start_modal.appendTo($('body'));
		}

	});


	// modal window
	$('.work').click(function (evt) {
		evt.preventDefault();
		if ($modal.is(':animated') || $modal.is(':visible')) {
			return;
		}

		$modal.openModal();

	});

	//window resize functions
	$(window).resize(function () {
		center_content();
		$('.video-wide').css({ width: '650px !important', height: '366px !important' });
		$('.video-wide').contents().css({ width: '650px !important', height: '366px !important' });
	});

})();

