var uploadModalBox;
var headphonesImages = new Array('images/headphones_xboxlowrider.png', 'images/headphones_ti.png', 'images/headphones_skpro.png', 
								'images/headphones_lowrider.png', 'images/headphones_hesh.png', 'images/headphones_fmj.png', 'images/headphones_doubleagent.png');
var headphonesLinks = new Array('http://www.skullcandy.com/shop/lowriders-for-xbox-360-p-95.html', 'http://www.skullcandy.com/shop/ti-p-7.html',
								'http://www.skullcandy.com/shop/sk-pro-p-13.html', 'http://www.skullcandy.com/shop/lowrider-p-26.html',
								'http://www.skullcandy.com/shop/hesh-p-5.html', 'http://www.skullcandy.com/shop/full-metal-jacket-p-30.html',
								'http://www.skullcandy.com/shop/double-agent-p-86.html');
								
var lastHeadphoneId = 0;

function closeModal() {
	uploadModalBox.display(0);
}

function uploadSubmit() {
	$$('div#uploadForm form')[0].submit();
}

function closeBox(id) {
	$(id).setStyle('display', 'none');
}

function registerSubmit() {
	firstname = $('firstName').value;
	lastname = $('lastName').value;
	usernamereg = $('usernameReg').value;
	passwordreg = $('passwordReg').value;
	emailreg = $('emailReg').value;
	terms = $('terms').checked;
	if(!terms) {
		alert('You must accept the terms to register.');
		return;
	}
	maillist = $('maillist').checked;
	$('ajaxLoader2').setStyle('display', 'block');
	var req = new Request({
				method: 'post',
				url: 'ajax.php',
				data: 'action=register&usernameReg=' + usernamereg + '&passwordReg=' + passwordreg + '&firstName=' + firstname + '&lastName=' + lastname + '&emailReg=' + emailreg +
								'&terms=' + terms + '&maillist=' + maillist,
				onSuccess: function(responseText) {
					var obj = JSON.decode(responseText);
					if(obj.result) {
						Cookie.write('logged', '1');
						Cookie.write('username', obj.username);
						Cookie.write('fullname', obj.fullname);
						$('registerBoxInner').setStyle('display', 'none');
						$('loginButton').setStyle('display', 'none')
						$('registerButton').setStyle('display', 'none');
						$('userMessage').set('html', 'Welcome ' + obj.fullname);
						$('userMessage').setStyle('display', 'block');
					}
					else {
						$('status1').set('html', obj.content);
					}																												
				},
				onComplete: function() {
					$('ajaxLoader2').setStyle('display', 'none');
				}
			});
	req.send();
}

function loginSubmit() {
	$('ajaxLoader').setStyle('display', 'block');
	username = $('usernameLogin').value;
	password = $('passwordLogin').value;
	var req = new Request({
		method: 'post',
		url: 'ajax.php',
		data: 'action=login&usernameLogin=' + username + '&passwordLogin=' + password,
		onSuccess: function(responseText) {
			var obj = JSON.decode(responseText);
			if(obj.result) {
				Cookie.write('logged', '1');
				Cookie.write('username', obj.username);
				Cookie.write('fullname', obj.fullname);
				$('loginBox').setStyle('display', 'none');
				$('loginButton').setStyle('display', 'none')
				$('registerButton').setStyle('display', 'none');
				$('userMessage').set('html', 'Welcome ' + obj.fullname);
				$('userMessage').setStyle('display', 'block');
			} else {
				$('status2').set('html', obj.content);
			}
		},
		onComplete: function() {
			$('ajaxLoader').setStyle('display', 'none');
		}
	});
	req.send();
}

function changeHeadphones() {
	var idx = lastHeadphoneId;
	while(lastHeadphoneId == idx) {
		idx = Math.floor(Math.random() * headphonesImages.length);
	}
	lastHeadphoneId = idx;
	
	$('headphones').setProperties({ href: headphonesLinks[idx]});
	$('headphones').getElement('img').setProperties({ src: headphonesImages[idx].src});
	setTimeout("changeHeadphones()", 20000);
}

var dropDownNavActive = false;
var dropDownCloseTimeout = null;
function closeDropDownNav() {
	$('dropDown').setStyle('display', 'none');
	dropDownNavActive = false;
}
function openDropDownNav() {
	$('dropDown').setStyle('display', 'block');
	dropDownNavActive = true;
}
function cancelCloseDropDownNavTimeout() {
	if(dropDownCloseTimeout) {
		window.clearTimeout(dropDownCloseTimeout);
		dropDownCloseTimeout = null;
	}
}

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

var mediaIndex = 0;
var playList = new Array();

function playMedia(mediaObj) {
	/*console.log(mediaObj.id);
	console.log(mediaObj);*/
	$$('#infoInner span')[0].innerHTML = mediaObj.title;
	$$('#infoInner p')[0].innerHTML = mediaObj.desc;
	$$('#infoInner img')[0].src = mediaObj.thumb;
	thisMovie('playerReplacement').setMedia(mediaObj.id, mediaObj.vendor);
}

function getPreviousMedia(){
	if(mediaIndex==0){
		mediaIndex = playList.length-1;
	} else {
		mediaIndex--;
	}
	playMedia(playList[mediaIndex]);
}

function getNextMedia(){
	if(mediaIndex==playList.length-1){
		mediaIndex = 0;
	} else {
		mediaIndex++;
	}
	playMedia(playList[mediaIndex]);		
}

window.addEvent('domready', function() {
	
	var bodyElement = $$('body')[0];
	var bodyId = bodyElement.get('id');
	var home = (bodyId == 'home');
	

	if(document.images) {
		for(i=0; i<headphonesImages.length; i++) {
			img = new Image(10, 10);
			img.src = headphonesImages[i];
			headphonesImages[i] = img;
		}		
	}

	
	$$('div#sideLists ul#buttons li a').addEvent('click', function() {
		$$('div#sideLists ul#buttons li a').each(function(elementItem) {
			if(elementItem != this) {
				$(elementItem.get('id') + 'List').setStyle('display', 'none');
				$(elementItem).removeClass('active');
			}
		});
		$(this.get('id') + 'List').setStyle('display', 'block');
		this.addClass('active');
		return false;	
	});
	
	$('dropDownNavButton').addEvent('click', function(e) {
		cancelCloseDropDownNavTimeout();
		if(dropDownNavActive)
			closeDropDownNav();
		else
			openDropDownNav();
		return false;
	});
	
	$$('a#dropDownNavButton, div#dropDown').addEvents({
		'mouseenter': cancelCloseDropDownNavTimeout,
		'mouseleave': function() {
			dropDownCloseTimeout = window.setTimeout(closeDropDownNav, 500);
		}
	});
	
	$$('document').addEvent('click', function(e) {
		if(dropDownNavActive)
			$('dropDown').setStyle('display', 'none');
	});
	
	var slideEffect = new Fx.Slide('commentForm').hide().slideOut();
	$('commentFormToggle').addEvent('click', function(e) {
		slideEffect.slideIn();
		this.setStyle('display', 'none');
		return false;
	});
	
	$$('div#commentForm form')[0].addEvent('submit', function(evt) {
		new Event(evt).stop();
		var valid = true;
		authorname = Cookie.read('fullname');
		if(authorname == null) {
			alert('Must be logged to comment.');
			valid = false;
		}
		var content = $('content').get('value');
		$('author_name').value = authorname;
		if(content.length == 0) {
			alert('Must write some comment.');
			valid = false;
		}

		if(valid) {
			var commentForm = $$('div#commentForm form')[0];
			commentForm.set('send', {
							url: 'ajax.php', 
							method: 'post',
							onSuccess: function(responseText) {
								var obj = JSON.decode(responseText);
								if(obj.success) {
									var commentsElement = $$('div#commentList ul')[0];
									commentsElement.set('html', obj.content + commentsElement.get('html'));
									$$('div#commentList ul li')[0].highlight();
									var c = parseInt($('commentCount').get('html'));
									$('commentCount').set('html', c + 1);						
								}
								else {
									alert(obj.content);
								}																												
							}
						});
			commentForm.send();
		}
		$('cancelComment').fireEvent('click');
	});
	
	$('cancelComment').addEvent('click', function() {
		$$('div#commentForm input[type=text]', 'div#commentForm textarea').each(function(element) {
			element.value = '';
			element.fireEvent('blur');
		});
		slideEffect.slideOut().chain(function() {
			$('commentFormToggle').setStyle('display', '');
		});
	});
	
	$$('div#commentForm input[type=text]', 'div#commentForm textarea').addEvents({
		'focus': function() {
			if(this.value == 'Your name' || this.value == 'Your email' || this.value == 'Your comment') {
				this.value = '';
				this.removeClass('unedited');
			}
		},
		'blur': function() {
			if(this.value.trim() == '') {
				this.addClass('unedited');
				this.value = 'Your ';
				switch(this.get('id')) {
					case 'author_name':
						this.value += 'name';
						break;
					case 'author_email':
						this.value += 'email';
						break;
					case 'content':
						this.value += 'comment';
						break;
				}
			}
		}
	})
	
	uploadModalBox = new SexyAlertBox();
	$$('#uploadNavBtn').addEvent('click', function() {
		uploadModalBox.info($('uploadContainer').get('html'));
		return false;
	});
	
	$$('a.searchButton').addEvent('click', function() {
		this.getParent('form').submit();
		return false;
	});
	
	var newSearchLink = $('newSearchLink');
	if(newSearchLink) {
		newSearchLink.addEvent('click', function() {
			$('searchBox2').setStyle('display', 'inline');
			this.setStyle('display', 'none');
			return false;
		});
	}
	
	$$('div#rating ul.star-rating li a').addEvent('click', function(ev) {
		new Event(ev).stop();
		var ratingCookie = Cookie.read('skullcandyRatingCookie');
		var alreadyRated = false;
		if(ratingCookie != null) {
			var alreadyRated = ratingCookie.split(';').some(function(id) {
				return id == selectedMediaId;
			});
		}
		else
			ratingCookie = '';
		if(alreadyRated) {
			uploadModalBox.info2('You already rated this media!');
			return false;
		}
		var rating = this.get('html');
		var req = new Request(
			{
				method: 'post', 
				url: 'ajax.php',
				data: 'action=rate&rating=' + rating + '&media_id=' + selectedMediaId + '&vendor_id=' + selectedMediaVendorId,
				onSuccess: function(responseText) {
					var obj = JSON.decode(responseText);
					if(obj.success) {
						$$('div#rating ul.star-rating li.current-rating')[0].setStyle('width', (obj.rating * 100) / 5 + '%');
						$$('div#rating span#ratingAverage')[0].set('html', obj.rating.toFixed(2));
						$$('div#rating span#ratingCount')[0].set('html', obj.count);
					}
				}
			});
		req.post();
		Cookie.write('skullcandyRatingCookie', ratingCookie + selectedMediaId + ';', {duration: 365});
	});
	
	$$('div#uploadForm form')[0].addEvent('submit', function(ev) {
		var valid = true;
		//new Event(ev).stop();
		$('ajaxLoader').setStyle('display', 'block');
		if($$('input#name')[0].value.trim() == '') {
			valid = false;
		}
		if($$('input#email')[0].value.trim() == '') {
			valid = false;
		}
		if($$('input#title')[0].value.trim() == '') {
			valid = false;
		}
		if($$('input#file')[0].value.trim() == '') {
			valid = false;
		}
		if(!valid) {
			alert('Must fill your name, your email, a title and a file.');
		}
		else {
			this.submit();
		}
	});
	
	$$('div#popularList ul li', 'div#recentList ul li', 'div#library table td').addEvent('click', function() {
		var linkAdd = this.getElements('a')[0].get('href');
		document.location = linkAdd;
	});
	
	$$('div#userBox a#registerButton').addEvent('click', function() {
		$('loginBox').setStyle('display', 'none');
		$('registerBoxInner').setStyle('display', 'block');
	});
	
	$$('div#userBox a#loginButton').addEvent('click', function() {
		$('registerBoxInner').setStyle('display', 'none');
		$('loginBox').setStyle('display', 'block');
	});
	
	switch(document.location.hash) {
		case '#contest':
			uploadModalBox.info($('uploadContainer').get('html'));
			break;
		case '#uploadCompleted':
			uploadModalBox.info2('Your video was uploaded without problems.');
			break;
		case '#uploadError':
	 		uploadModalBox.info2('There was a problem uploading your file. Please contact the Skullcandytv.com support.');
		default:
			break;
	}
});