$(function(){
	bgFade();
	searchSlide();
	boxSlide();
});

function boxSlide(){
	var openClass = 'open';
	$('a.slide-link').each(function(){
		var _this = $(this);
		var box = _this.parent().find('.add');
		_this.click(function(){
			if($(this).hasClass(openClass)){
				$(this).removeClass(openClass);
				box.slideUp(700);
			}
			else{
				$(this).addClass(openClass);
				box.slideDown(700);
			}
			return false;
		});
	});
}

function searchSlide(){
	$('a.search-link').each(function(){
		var _this = $(this);
		var _thisW = _this.width();
		var list = _this.parents('ul.top-nav');
		var box = list.find('.search-block').css({margin:0, display:'block', width:'auto'});
		var _w = box.width();
		box.css({width:0});
		box.parent().width(_thisW);
		var ww = _w+10;
		
		_this.click(function(){
			if($(this).data('open')){
				$(this).data('open', false);
				box.parent().animate({width:'-='+ww}, {queue:false, duration:700})
				box.animate({width: 0, marginLeft:0, marginRight:0}, {queue:false, duration: 700, complete: function(){
					box.hide();
				}});
			}
			else{
				$(this).data('open', true);
				box.parent().animate({width:'+='+ww}, {queue:false, duration:700})
				box.css({width:box, 'display':'block'}).animate({width: _w, marginLeft:0, marginRight:4}, {queue:false, duration: 700});
			}
			return false;
		});
	});
}

function bgFade(){
	imgStretch();
	initFadeGallery();
	function imgStretch(){
		// stretch images
		var hold = document.getElementById('bg-page');
		if (hold) {
			var imgs = hold.getElementsByTagName('img');
			for (var i = 0; i < imgs.length; i++) {
				// stretch image method
				imageStretcher.stretch(imgs[i]);
			}
			// unstretch image method
			// imageStretcher.unstretch(imgs[1]);
			
			// resize wrapper properly
			imageStretcher.setBgHolder(hold);
		}
	}
	function initFadeGallery(){
		var set = jQuery('#bg-page img'),
			animSpeed = 1200,
			delay = 7000,
			curInd = 0,
			prevInd = 0,
			timer;
		set.hide().eq(curInd).show();
		function nextSlide() {
			prevInd = curInd;
			if(curInd < set.length-1) curInd++; else curInd = 0;
			set.eq(prevInd).fadeOut(animSpeed);
			set.eq(curInd).fadeIn(animSpeed);
			autoSlide();
		}
		function autoSlide() {
			if(timer) clearTimeout(timer);
			timer = setTimeout(nextSlide,delay);
		}
		autoSlide();
	}
}

// image stretcher module
var imageStretcher = (function(){
	var viewWidth, viewHeight, timer,
		images = [], holders = [];

	function addImage(img) {
		recalcSize();
		images.push(img);
		img.style.msInterpolationMode = 'bicubic'; // IE7 fix
		if(img.comlete) {
			getRatio(img, resizeImage);
		} else {
			img.onload = function(){
				getRatio(img, resizeImage);
				img.onload = null;
			}
			img.src = img.src; // IE Fix
		}
	}
	function removeImage(img) {
		for(var i=0; i < images.length; i++) {
			if(images[i] === img) {
				images.splice(i,1);
				return;
			}
		}
	}
	function addHolder(obj) {
		recalcSize();
		holders.push(obj);
		resizeHolder.apply(obj);
	}
	function removeHolder(obj) {
		for(var i=0; i < holders.length; i++) {
			if(holders[i] === obj) {
				holders.splice(i,1);
				return;
			}
		}
	}

	function getRatio(img, cb) {
		var newImg = new Image();
		newImg.onload = function() {
			img.ratio = newImg.width / newImg.height;
			if(typeof cb === 'function') cb.apply(img)
			newImg.onload = null;
		}
		newImg.src = img.src;
	}
	function resizeImage(img) {
		var ratio = this.ratio;
		var slideWidth = viewWidth;
		var slideHeight = slideWidth / ratio;
		if(slideHeight < viewHeight) {
			slideHeight = viewHeight;
			slideWidth = slideHeight * ratio;
		}
		this.style.width = slideWidth+'px';
		this.style.height = slideHeight+'px';
		this.style.top = (viewHeight-slideHeight)/2+'px';
		this.style.left = (viewWidth-slideWidth)/2+'px';
	}
	function resizeHolder(obj) {
		this.style.width = viewWidth + 'px';
		this.style.height = viewHeight + 'px';
		this.style.overflow = 'hidden';
	}
	function resetHolder(obj) {
		this.style.width = 0;
		this.style.height = 0;
	}
	function recalcSize() {
		for(var i=0; i< holders.length; i++) resetHolder.apply(holders[i]);
		viewWidth = getPageWidth();
		viewHeight = getPageHeight();
	}
	function handleResize() {
		clearTimeout(timer);
		timer = setTimeout(function(){
			recalcSize();
			for(var i=0; i< images.length; i++) resizeImage.apply(images[i]);
			for(var i=0; i< holders.length; i++) resizeHolder.apply(holders[i]);
		},13);
	}

	// util functions
	function addHandler(object, event, handler) {
		if (typeof object.addEventListener != 'undefined') object.addEventListener(event, handler, false);
		else if (typeof object.attachEvent != 'undefined') object.attachEvent('on' + event, handler);
	}
	function getPageHeight() {
		return Math.max(
			Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
			Math.max(document.body.clientHeight, document.documentElement.clientHeight)
		);
	}
	function getPageWidth() {
		return Math.max(
			Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
			Math.max(document.body.clientWidth, document.documentElement.clientWidth)
		);
	}
	addHandler(window, 'resize', handleResize);

	// methods
	return {
		stretch: addImage,
		unstretch: removeImage,
		setBgHolder: addHolder,
		unsetBgHolder: removeHolder
	}
})();

// 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:'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();
