var APP = false;

var Basket = {
	
	_overlay: null,
	_content: null,
	
	closeAll: function() {
		$$('.listen_mb_wrap').each(function(el) {
			el.style.display = 'none';	
		}, this);
	},
	
	// Get checked box
	// Read checkbox elements in basketSongListForm
	// @return array of song elements
	_getCheckedSongNums: function() {
		var checkboxes = document.basketForm.elements['song_nums[]'];
		var songArray = new Array();
		
		if (checkboxes.length == undefined) {
			
			// If there is only one checkbox element
			if (checkboxes.checked == true) {
				songArray[0] = checkboxes.value;
			}
			
		} else if (checkboxes.length > 0) {
			
			var count = 0;
			for (var i=0; i<checkboxes.length; i++) {
				if (checkboxes[i].checked == true) {
					songArray[count++] = checkboxes[i].value;
				}
			}
		}
		
		return songArray;
	},
	
	updatePrice: function() {
		// Checkbox elements
		var songEles = this._getCheckedSongNums();
		// Count checked boxes
		var countChecked = songEles.length;
		// Total price
		var totalPrice = countChecked * 99;
		// User's subscription
		var userSubscription = UserLogin.getLogininfo().subscription;
		// User's shakecash balance
		var userShakecash = UserLogin.getLogininfo().shakecash;
		
		if ($('basket-totalcount')) {
			$('basket-totalcount').setHTML(countChecked);
		}
		
		if ($('basket-totalprice')) {
			$('basket-totalprice').setHTML(totalPrice);	
		}
		
		if (!userSubscription) {
			var offClassName = userShakecash >= totalPrice ? 'none' : 'block';
			var onClassName = userShakecash >= totalPrice ? 'block' : 'none';
			
			if ($('basket-download-off')) {
				$('basket-download-off').setStyle('display', offClassName);
			}
			if ($('basket-download-on')) {
				$('basket-download-on').setStyle('display', onClassName);
			}	
		}
	},
	
	initOverlay: function() {
		
		if (!this._overlay) {
			
			var _overlay = new Element('div');
			_overlay.addClass('downloadOverlay');
			
			var close = new Element('div');
			close.addClass('close');
			
			var _content = new Element('div');
			
			_overlay.appendChild(close);
			_overlay.appendChild(_content);
			$(document.body).appendChild(_overlay);
			
			this._overlay = _overlay;
			this._content = _content;
			
			close.addEvent('click', function() {
				$(document.body).removeChild(this._overlay);
				this._overlay = null;
				Cover.hide();
			}.bind(this));
		}
	},
	
	/*
	 * Add song(s) to basket
	 * update: 12/1/09
	 *         replace login module
	 */
	addSong : function(SONG_NUM, BUY_TYPE, LAYERID, LAYERNAME, LAYERCOUNT) {
		
		UserLogin.logincheck(function() {
			
			//LoadingOverlay.start(document.body);
			
			//var Param = { 'MODE': 'Call' };
			//Param.Type =  "Page";
			//Param.SONG_NUM = SONG_NUM;
			//Param.BUY_TYPE = BUY_TYPE;
			//Param.LAYERID = LAYERID;
			//Param.onComplete = function() {
			//	if(LAYERNAME != undefined) {
			//		for(var idx=1;idx<=LAYERCOUNT;idx++) {
			//			var TARGETNAME = "ShareContent" + idx;
			//			if(TARGETNAME != LAYERNAME) {
			//				$(TARGETNAME).innerHTML = "";
			//			}
			//		}
			//	}
			//	this.closeAll();
			//	if(LAYERID == 1) {
			//		$('buy_mp3_step1').style.display = 'block';	
			//	} else if(LAYERID == 2 ) {
			//		$('buy_ringtone_step1').style.display = 'block';
			//	}
			//	
			//}.bind(this);
			
			var _this = this;
			new Ajax('/Listen/Song/SongContent/ajax.buymp3.php', {
				method: 'post',
				//data: Param,
				onComplete: function(response) {
					LoadingOverlay.end();
					Cover.show();
					_this.initOverlay();
					_this._content.setHTML(response);
					
					//var height = UI.getBounds(_this._overlay).height/2;
					//_this._overlay.setStyle('margin-top','-'+height+'px');
				}
			}).request();
			
			//if(LAYERID == 1) {
			//	if(LAYERNAME != undefined) {
			//		AutoRun.setDocument($(LAYERNAME), Param , '/Listen/Song/SongContent/ajax.buymp3.php');
			//	} else {
			//		new Ajax('/Listen/Song/SongContent/ajax.buymp3.php', {
			//			method: 'post',
			//			data: Param,
			//			onComplete: function(response) {
			//				Cover.show();
			//				_this.initOverlay();
			//				_this._content.setHTML(response);
			//				var height = UI.getBounds(_this._overlay).height/2;
			//				_this._overlay.setStyle('margin-top','-'+height+'px');
			//				LoadingOverlay.end();
			//			}
			//		}).request();
			//		//AutoRun.setDocument($('ShareContent'), Param , '/Listen/Song/SongContent/ajax.buymp3.php');
			//	}
			//} else {	
			//	if(LAYERNAME != undefined) {
			//		AutoRun.setDocument($(LAYERNAME), Param , '/Listen/Song/SongContent/ajax.buyringtone.php');
			//	} else {
			//		AutoRun.setDocument($('ShareContent'), Param , '/Listen/Song/SongContent/ajax.buyringtone.php');
			//	}
			//}
			
		}.bind(this), $('main_box_body'));
	},
	
	addAlbum : function(ALBUM_NUM, BUY_TYPE) {
		//if(!Login.getLogin())
		//{
		//	alert('Please login first.');
		//	location.href = '/Login';
		//	return;
		//}
		
		UserLogin.logincheck(function() {
			LoadingOverlay.start(document.body);
			
			var Param = {  'MODE' : 'Call'  };
			
			Param["Type"] =  "Page";
			Param['ALBUM_NUM'] = ALBUM_NUM;
			Param['BUY_TYPE'] = BUY_TYPE;
			//Param.onComplete = function ()
			//{
			//	//alert('x');
			//	//this.closeAll();
			//	//$('buy_mp3_step1').style.display = 'block';
			//}.bind(this);
			
			var _this = this;
			new Ajax('/Listen/Album/AlbumContent/ajax.buyplaylist.php', {
				method: 'post',
				data: Param,
				onComplete: function(response) {
					Cover.show();
					_this.initOverlay();
					_this._content.setHTML(response);
					var height = UI.getBounds(_this._overlay).height/2;
					_this._overlay.setStyle('margin-top','-'+height+'px');
					LoadingOverlay.end();
				}
			}).request();
			
			//AutoRun.setDocument($('ShareContent'), Param , '/Listen/Album/AlbumContent/ajax.buyplaylist.php');
			
		}.bind(this), $('main_box_body'));
	},
	
	addSongsFromCart: function() {
		
		UserLogin.logincheck(function() {
			LoadingOverlay.start(document.body);
			
			var _this = this;
			
			new Ajax('/xhr.php?a=checkout', {
				method: 'post',
				//data: param,
				onComplete: function(response) {
					Cover.show();
					
					_this.initOverlay();
					_this._content.setHTML(response);
					
					var height = UI.getBounds(_this._overlay).height/2;
					_this._overlay.setStyle('margin-top','-'+height+'px');
					
					LoadingOverlay.end();
				}
			}).request();
			
		}.bind(this), $('main_box_body'));
	},
	
	//_songListToStr: function(songNums) {
	//	var strVal = '';
	///	if (typeof songNums == 'string') {
	//		strVal = songNums;
	//	} else {
	//		if (!songNums.length) {
	//			strVal += (strVal ? ','  : '') . songNums.value;
	//		} else {
	//			for (var i=0; i<songNums.length; i++) {
	//				strVal += (strVal ? ','  : '') + songNums[i].value;
	//			}
	//		}
	//	}
	//	return strVal;
	//},
	
	// @param input checkbox
	_checkboxToStr: function(songNums) {
		
		var strVal = '';
		
		if (typeof songNums == 'string') {
			
			strVal = songNums;
			
		} else {
			
			if (!songNums.length) {
				strVal += (strVal ? ','  : '') . songNums.value;
			} else {
				for (var i=0; i<songNums.length; i++) {
					strVal += (strVal ? ','  : '') + songNums[i].value;
				}
			}
		}
		
		return strVal;
	},
	
	download: function(userNum) {
		// Prepare paramter
		var songEles = this._getCheckedSongNums();
		var param = songEles.toString();
		
		// Lookup user's subscription
		// and determine purchase type
		if (!UserLogin.getLogininfo().subscription) {
			// use subscription
			this._downloadAfterBuy(param,userNum);
		} else {
			// use buy
			this._downloadAfterSubscription(param,userNum);
		}	
	},
	
	_downloadAfterBuy: function(param, userNum) {
		LoadingOverlay.start(document.body);
		var _this = this;
		new Ajax('/xhr.php?a=buy', {
			method: 'post',
			data: 'songs='+param,
			onComplete: function(response) {
				LoadingOverlay.end();
				var json = eval("("+response+")");
				if (json.result == "success") {
					_this._downloadNow(param, userNum);
				} else {
					// error
					// alert('');
				}
			}
		}).request();
	},
	
	_downloadAfterSubscription: function(param, userNum) {
		LoadingOverlay.start(document.body);
		var _this = this;
		new Ajax('/xhr.php?a=subscription', {
			method: 'post',
			data: 'songs='+param,
			onComplete: function(response) {
				LoadingOverlay.end();
				var json = eval("("+response+")");
				if (json.result == "success") {
					_this._downloadNow(param, userNum);
				} else {
					// error
					// alert('');
				}
			}
		}).request();
	},
	
	_downloadNow: function(param, userNum) {
		
		if (param && userNum) {
			var url = 'http://mp3.musicshake.com/procfile/download.php';
			location.href = url+'?SONG_NUM='+param+'&USER_NUM='+userNum;
		} else {
			alert('We were not able to start download.\nPlease try again.');	
		}
	},
	
	deleteSong : function(SONG_NUM, BUY_TYPE,ALBUM_NUM)
	{
		var Param = {
			'MODE' : 'Call', 
			'Type' : 'Page',
			'MODE' : 'DELETE',
			'SONG_NUM' : SONG_NUM,
			'BUY_TYPE' : BUY_TYPE,
			'ALBUM_NUM' : ALBUM_NUM
		};
		
		AutoRun.setDocument($('ShareContent'), Param, '/APP/Buy_Song/Basket.php');
	},
		
	ListLoad : function(BUY_TYPE)
	{
		var Param = {
			'MODE' : 'Call', 
			'Type' : 'Page',
			'BUY_TYPE' : BUY_TYPE
		};
		
		AutoRun.setDocument($('ShareContent'), Param, '/APP/Buy_Song/Basket.php');
	},
	
	Buy : function(BUY_TYPE,CATEGORY)
	{
		if(!confirm("Would you like to buy the song?")) return false;
		
		var Result = Ajax.exec('/APP/Buy_Song/Buy.php',{'BUY_TYPE' : BUY_TYPE} );
		
		eval(Result.text);
		
		if(Re.STATUS == "OK" ) {
			
			this.closeAll();
			
			if(CATEGORY == "MP3") {
				$('buy_mp3_step2').style.display = "block";
			} else if(CATEGORY == "ALBUM") {
				$('buy_mp3_step2').style.display = "block";
			} else {
				$('buy_ringtone_step2').style.display = "block";
			}
			
			if($('USER_CASH')) {
				$('USER_CASH').innerHTML = money(Re.USER_CASH);
			}
			
			$('TOP_USER_CASH').innerHTML = money(Re.USER_CASH);
			
		} else {
			
			alert(Re.ERROR_MESSAGE);
		}
	},
	
	close : function()
	{
		if(APP)
			self.close();
		else
			Pop.close();
	},
	
	CashOpen : function()
	{
		if(APP)
		{
			var shape = "left=70,top=10,toolbar=no,location=no,directories=no,status=no,";
				shape += "menubar=no,scrollbars=no,resizable=no";
				shape += ",width=606,height=550";
			window.open('/APP/Cash_Charge', 'CashCharge', shape);
		}
		else
		{
			location.href = '/Store/Cash';
		}
	},
	
	BuySongOpen : function()
	{
		if(APP)
		{
			window.open('/MyMusicShake/MySong/Buy_Song', '', '');
			self.close();
		}
		else
		{
			location.href = '/MyMusicShake/MySong/Buy_Song';
		}
	},
	
	CashUseOpen : function()
	{
		if(APP)
		{
			window.open('/MyMusicShake/Cash/Use/', '', '');
			self.close();
		}
		else
		{
			location.href = '/MyMusicShake/Cash/Use/';
		}
	}
}
