/* copyright tumimusic.com */
window.onload = function() {
	if (window.RPlayer) RPlayer.init();
	if (window.GoToTop) GoToTop.init();
	if (window.YouTube) YouTube.init();
	if (window.Helptip) Helptip.init();
	if (window.Search) Search.init();
	if (window.TumiStore) TumiStore.init();
	if (window.ContactForm) ContactForm.init();
	if (window.CustomerInfoForm) CustomerInfoForm.init();
}

/* scroll to top */
var GoToTop = {
	image: '/images/gototop.png',
	scrollTime: 1000,//milli seconds
	scrollClock: 10,
	initiated: false,
	init: function() {
		if (this.initiated) return;
		var div = document.createElement('div');
		this.link = document.createElement('a');
		this.link.href = '#Top';
		var img = document.createElement('img');
		img.src = this.image;
		img.alt = "Top";
		this.link.appendChild(img);
		div.appendChild(this.link);
		div.id = 'gototop';
		document.body.appendChild(div);
		var gototop = this;
		this.link.onmousedown = function() {
			gototop.scroll();
			this.blur();
			return false;
		};
		this.link.onclick = function() {
			return false;
		};
		this.link.style.display = 'block';
		window.onscroll = function() {
			gototop.refresh();
		};
		this.refresh();
		this.initiated = true;
	},
	refresh: function() {
		var scroll = 0;
		try {
			scroll = window.pageYOffset;
		}
		catch (e) {
			try {
				scroll = window.page.scrollTop;
			}
			catch(e) {}
		}
		this.link.style.display = scroll > 300 ? 'block' : 'none';
	},
	scroll: function() {
		if (this.isScrolling) return;
		this.isScrolling = true;
		var scrollPosition = this.getScroll();
		if (scrollPosition == 0) return;
		var steps = this.scrollTime / this.scrollClock;
		var a = 4 * scrollPosition / (steps * steps);//s = 1/2 at^2
		var t = 0;
		while (true) {
			var s = 0.5 * a * t * t; //s = 1/2 at^2
			if (scrollPosition < 2 * s) break;
			window.setTimeout('GoToTop.scrollTo(' + (scrollPosition - s) + ')', this.scrollClock * t);
			window.setTimeout('GoToTop.scrollTo(' + s + ')', this.scrollTime - this.scrollClock * t);
			t++;
		}
	},
	getScroll: function() {
		var scrOfY = 0;
		if (typeof(window.pageYOffset) == 'number') {
			scrOfY = window.pageYOffset;
		}
		else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			scrOfY = document.body.scrollTop;
		}
		else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			scrOfY = document.documentElement.scrollTop;
		}
		return scrOfY;
	},
	scrollTo: function(y) {
		window.scrollTo(0, y);
		if (y <= 0) this.isScrolling = false;
	}
}

/* helptip */
var Helptip = {
	initiated: false,
	init: function() {
		if (this.initiated) return;
		var img = document.getElementsByTagName('img');
		for (var i = img.length - 1; i >= 0; i--)
		if (img[i].className.match(/^helptip/))
		this.add(img[i], false);
		var a = document.getElementsByTagName('a');
		for (var i = a.length - 1; i >= 0; i--)
		if (a[i].rel && a[i].rel == 'helptip')
		this.add(a[i], true);
		this.initiated = true;
	},
	add: function(img, isLink) {
		new HelpTip(img, isLink);
	}
}

function HelpTip(img, isLink) {

	//variables
	this.img = img;
	this.tip = img.title;
	this.isLink = isLink;
	img.title = '';
	if (this.tip == '') return; //exit if no tip to display
	this.offset = {
		x: 0,
		y: 0
	};
	this.show = function (e) {
		var mouse = this.getMouse(e);
		var x = y = 0;
		this.div = document.createElement('div');
		document.body.appendChild(this.div);
		y = mouse.y>10 && mouse.y<450 ? mouse.y - 4 : mouse.y + 4;
		var messageHeigth = (this.tip.length / 20) * 8 + 10;
		var chunks = this.tip.split('||');
		var mLength = 0;
		for (var i = 0; i < chunks.length; i++) {
			var len = chunks[i].length;
			if (len >= mLength)
				mLength = len;
		}
		var messageWidth = mLength > 36 ? 180 : mLength*5;

		if (mouse.y + messageHeigth > screen.availHeight - 200) y = mouse.y - messageHeigth;
		if (mouse.x < screen.availWidth - 240) x = mouse.x + 20;
		else {
			x = mouse.x - messageWidth + "px";
			y = mouse.y + 20;
		}
		this.div.className = 'helptip';
		this.div.innerHTML = this.tip;
		this.div.style.display = 'block';
		this.div.style.maxWidth = '180px';
		this.offset.x = x - mouse.x;
		this.offset.y = y - mouse.y;
		this.setPosition(x, y);
	};
	this.hide = function () {
		if (this.div && this.div.parentNode) this.div.parentNode.removeChild(this.div);
	};
	this.slide = function (e) {
		var mouse = this.getMouse(e);
		if (this.div) {
			this.setPosition(mouse.x + this.offset.x, mouse.y + this.offset.y);
		}
	};
	this.getMouse = function (e) {
		e = e || window.event;
		var mouse = {};
		if(e.pageX||e.pageY) {
			mouse.x = e.pageX;
			mouse.y = e.pageY;
		}
		else if(e.clientX||e.clientY) {
			mouse.x = e.clientX + document.body.scrollLeft+document.documentElement.scrollLeft;
			mouse.y = e.clientY + document.body.scrollTop+document.documentElement.scrollTop;
		}
		return mouse;
	};
	this.setPosition = function(x,y) {
		this.div.style.left = x + 'px';
		this.div.style.top = y + 'px';
	};
	var helpTip = this;
	this.img.onmouseover = function (event) {
		helpTip.show(event);
	};
	this.img.onmouseout = function () {
		helpTip.hide();
	};
	this.img.onmousemove = function (event) {
		helpTip.slide(event);
	};
	this.img.onclick = function() {
		if (helpTip.isLink) helpTip.hide();
	};
}

/* youtube */
var YouTube = {
	initiated: false,
	init: function() {
		if (this.initiated) return;
		var links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++) {
			if (links[i].className == 'videolink') {
				if (!this.videos) this.videos = Array();
				var id =  links[i].href.split('?v=')[1];
				this.videos[id] = new Video(id);
				links[i].onclick = function() {
					return !YouTube.showVideo(this.href.split('?v=')[1]);
				}
			}
		}
		this.initiated = true;
	},
	showVideo: function(id) {
		if (this.videos && this.videos[id]) {
			this.videos[id].show();
			return true;
		}
		return false;
	},
	playVideo: function(id) {
		if (this.videos && this.videos[id]) {
			this.videos[id].play();
			return true;
		}
		return false;
	}
}
function onYouTubePlayerReady(playerId) {
	YouTube.playVideo(decodeURIComponent(playerId).substr(9));
}
function beforeYouTubeLoading() {
}
function Video(id) {
	this.videoId = id;
	if (window.google == undefined) {
		DHTML.alert('Google API not loaded. Please refresh the page.');
		throw 'Google API not loaded.';
	}
	this.videoBlock = document.createElement('div');
	this.videoBlock.className = 'videoblock';
	this.layer = document.createElement('div');
	this.layer.className = 'youtube_layer';
	this.videoDiv = document.createElement('div');
	this.videoDiv.style.position = 'fixed';
	this.videoDiv.className = 'video';
	this.replacementDiv = document.createElement('div');
	this.replacementDiv.id = 'youtube_video_div_' + this.videoId;
	this.replacementDiv.innerHTML = 'You need <a href="http://get.adobe.com/flashplayer/">Flash Player 8+</a> to view this video, or click <a href="http://www.youtube.com/watch?v=' + this.videoId + '">here</a> if you are using a handheld device.';
	this.videoDiv.appendChild(this.replacementDiv);
	this.videoCover = document.createElement('div');
	this.videoCover.className = 'video_cover';
	this.videoBlock.appendChild(this.layer);
	this.videoBlock.appendChild(this.videoDiv);
	this.videoBlock.appendChild(this.videoCover);	
	document.body.appendChild(this.videoBlock);
	var params = {allowScriptAccess: "always", bgcolor: "#cccccc"};
	var video = this;
	var atts = {id: 'v' + video.videoId};
	swfobject.embedSWF('http://www.youtube.com/v/' + video.videoId + '?border=0&amp;enablejsapi=1&amp;playerapiid=ytplayer_' + video.videoId, video.replacementDiv.id, "640", "385", "8", null, null, params, atts);
	this.show = function() {
		if (window.beforeYouTubeLoading) {
			beforeYouTubeLoading();
		}
		this.videoBlock.style.display = 'block';
	}
	this.play = function() {
		this.videoBlock.style.display = 'block';
		try {
			document.getElementById('v' + this.videoId).playVideo();
		}
		catch (e) {
			DHTML.alert(e);
		}
	}
	this.stop =  function() {
		try {
			document.getElementById('v' + this.videoId).stopVideo();
			document.getElementById('v' + this.videoId).stopVideo();
		}
		catch (e) {
			DHTML.alert(e);
		}
		this.videoBlock.style.display = 'none';
	}
	this.layer.onclick = function() {
		video.stop();
	}
}

/* Search button */
var Search = {
	defaultValue: '',
	initiated: false,
	init: function() {
		if (this.initiated) return;
		var div = $('search');
		var forms = div.getElementsByTagName('form');
		if (!forms || !forms[0]) {
			return;
		}
		this.form = forms[0];
		this.form.reset();
		this.input = this.form.getElementsByTagName('input')[0];
		this.defaultValue = this.input.value;
		this.input.className == 'presearch';
		this.input.onfocus = function() {
			if (this.className == 'presearch') {
				this.className = 'postsearch';
				this.value = '';
			}
		}
		this.input.onblur = function() {
			if (this.className == 'postsearch' && this.value == '') {
				this.className = 'presearch';
				this.form.reset();
			}
		}
		this.form.onsubmit = function() {
			return this.search.value != '' && this.search.value != Search.defaultValue;
		}
		this.initiated = true;
	}
}

/* Ajax class */
function Ajax(url) {

	if (!url) return;
	this.url = url;
	this.http = false;
	try	{
		this.http = new XMLHttpRequest();
	}
	catch (e) {
		try {
			this.http = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e1) {
			this.http = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (!this.http) {
		DHTML.alert('Suppot for Ajax not found');
		return;
	}

	this.post = function(params) {
	
		try {
			//onreadystatechange
			this.http.onreadystatechange = function () {
				if (this.readyState==4 || this.readyState=="complete") {
				
					DHTML.loading(false);
					if (this.status == 200) {
						var res = this.responseXML;
						if (!res) {
							DHTML.alert('Server Error: \n' + this.responseText.replace(/<[^>]*>/g, ''));
							return;
						}
						new Response(res);
					}
					else if (this.status == 404) DHTML.alert('Server not found');
					else DHTML.alert('Error in connection');
				}
				else {
					DHTML.loading(true);
				}
			}
	
			var requestType = !params ? 'get' : 'post';
			var random = '&random=' + Math.random();
			this.http.open(requestType, this.url + random, true);
			if (requestType == 'post') {
				this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
				this.http.setRequestHeader("Content-length", params.length);
				this.http.setRequestHeader("Connection", "close");
				this.http.send(params);
			}
			else {
				this.http.setRequestHeader("Connection", "close");
				this.http.send();
			}
			return true;
		}
		catch (e) {
			alert(e);
			try { DHTML.loading(true);} catch(e1) {}
			return false;
		}
	}
	
	this.get = function() {
		return this.post(false);
	}

	this.submit = function(form) {
		var inputs = form.getElementsByTagName('input');
		var textareas = form.getElementsByTagName('textarea');
		var selects = form.getElementsByTagName('select');
		
		var string = '';
		for (var i = 0; i < inputs.length; i++) {
			switch (inputs[i].type) {
				case 'checkbox':
				case 'radio':
					if (inputs[i].checked) string += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
					break;
				default:
					string +=  '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
					break;			
			}
		}
		for (var i = 0; i < textareas.length; i++) {
			string +=  '&' + textareas[i].name + '=' + encodeURIComponent(textareas[i].value);
		}
		for (var i = 0; i < selects.length; i++) {
			var name = !!selects[i].getAttribute('multiple') ? selects[i].name + '[]' : selects[i].name;
			var selecteds = Array();
			while (selects[i].selectedIndex != -1) {
				string += '&' + name + '=' + encodeURIComponent(selects[i].options[selects[i].selectedIndex].value);
				if (!selects[i].getAttribute('multiple')) break;
				selecteds.push(selects[i].selectedIndex);
				selects[i].options[selects[i].selectedIndex].selected = false;
			}
			if (!!selects[i].getAttribute('multiple') && selecteds.length) {
				for (var j in selecteds) {
					selects[i].options[selecteds[j]].selected = true;
				}
			}
		}
		this.post(string);
	}
}

function Response(xml) {
	
	if (!xml) {
		DHTML.alert('Invalid XML Response');
		return;
	}
	
	var response = xml.getElementsByTagName('response')[0];
	
	if (!response) {
		DHTML.alert('Invalid XML response');
		return;
	}
	var requestType = response.getAttribute('type');
	switch(requestType) {
		case 'contact':
			if (window.ContactForm && window.ContactForm.parseResponseXML)
			ContactForm.parseResponseXML(response);
		break;
		case 'store':
			if (window.TumiStore && window.TumiStore.parseResponseXML)
			TumiStore.parseResponseXML(response);
		break;
		//more to come... 
	}
}

/* Layer object acts as a transparent layer behind the popup */
function Layer(showLoading) {
	var opacity = 50;
	this.div = document.createElement('div');
	this.div2 = false;
	this.div.className = 'layer';
	DHTML.setOpacity(this.div, opacity);
	document.body.appendChild(this.div);
	if (showLoading) {
		this.div2 = document.createElement('div');
		this.div2.className = 'loading_bar';
		document.body.appendChild(this.div2);
	}
	this.remove = function(time) {
		if (!!time) {
			DHTML.fadeOut(this.div, time, true, opacity);
			if (this.div2 !== false) DHTML.fadeOut(this.div2, time, true);
			return;
		}
		this.div.parentNode.removeChild(this.div);
		if (this.div2 !== false) this.div2.parentNode.removeChild(this.div2); 
	}
}

var DHTML = {
	divs: Array(),
	alert: function(message) {
		alert(message); //can be modified for some sophisticated look
	},
	loading: function(flag) {
		if (flag && this.visible) return;
		if (!flag && !this.visible) return;
		if (flag) {
			this.layer = new Layer(true);
		}
		else {
			if (this.layer) this.layer.remove();
		}
		this.visible = flag;
	},
	fadeOut: function(div, time, doRemove, initialOpacity) {
		var timeInterval = 50; //milliseconds
		var uniqueId = 'id' + Math.floor(Math.random() * 1000000);//for saving reference
		this.divs[uniqueId] = div;
		this.divs[uniqueId].style.display = 'block';
		var opacity = !!initialOpacity ? initialOpacity : 100;
		var decrement = time > timeInterval ? opacity * timeInterval / time : opacity;
		var i = 1;
		while (opacity > 0) {
			opacity -= decrement;
			window.setTimeout('DHTML.setOpacity(DHTML.divs["'+uniqueId+'"], "'+opacity+'")', timeInterval * i++);
		}
		var func = doRemove ? 'DHTML.divs["'+uniqueId+'"].parentNode.removeChild(DHTML.divs["'+uniqueId+'"]);' : 'DHTML.divs["'+uniqueId+'"].style.display="none";DHTML.setOpacity(DHTML.divs["'+uniqueId+'"], "100");';
		window.setTimeout(func + 'delete DHTML.divs["'+uniqueId+'"];', timeInterval * i);
	},
	setOpacity: function(div, opacity) {
		opacity = opacity > 0 ? opacity : 0;
		try { div.style.opacity = (opacity/100) + '';} catch (e) {}
		try { div.style.filters.alpha.opacity = opacity + '';} catch (e) {}
		try { div.style.filter.alpha.opacity = opacity + '';} catch (e) {}
		try { div.style.filter = 'alpha(opacity=' + opacity + ')';} catch (e) {}
	}
}



/* getElementById */
function $(id) {
	if (document.getElementById(id))
	return document.getElementById(id);
	return false;
}
