function getXMLHttpRequest() {
	if (window.ActiveXObject) {
		try {
			return new ActiveXObject('Msxml2.XMLHTTP');
		} catch(e) {
			try {
				return new ActiveXObject('Microsoft.XMLHTTP');
			} catch(e1) { return null; }
		}
	} else if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else {
		return null;
	}
}

var cmt_req;
function CommentResult(){
	if(cmt_req.readyState == 4) {
		if(cmt_req.status == 200){
			var htmlText = cmt_req.responseText;
			$('#replycontent')[0].innerHTML = htmlText;
		} 
		else{
			alert("잠시후 다시 시도해주세요.");
		}
	}
}

function imgReset(obj) {
    obj.blur();
    $(obj).parents().filter('form')[0].reset();
    return false;
}

function move(url) {
    window.location.href = url;
}

function statusAlert(message) {
    var obj =  document.getElementById('statusAlert');
    if(!obj) {
        var obj = document.createElement('div');
        obj.id = 'statusAlert';
        obj.style.backgroundColor = 'red';
        obj.style.zIndex = 99;
        obj.style.position = 'absolute';
        obj.style.top = 0;
        obj.style.left = '50%';
        obj.style.height = '3em';
        obj.style.padding = '5px';
        document.getElementsByTagName('body')[0].appendChild(obj);
    }
    obj.innerHTML = message;
}


function getAlbumsByArtist(obj) {
	var artistId = obj.value;
    
    var album = document.getElementById('albums');
    album.disabled = true;
    album.innerHTML = '<option>로딩 중</option>';
    $.ajax({
            url :  '/manager/album/getByArtist/'+artistId,
            type : 'get',
            dataType : 'json',
            success : function(r) {
                  var album = document.getElementById('albums');
                  album.innerHTML = '';
                  if(r.length == 0) {
                      var optionObj = document.createElement('option');
                      optionObj.value = null;
                      optionObj.innerHTML = '등록된 앨범이 없습니다';  
                      album.appendChild(optionObj);
                  } else {
                      var optObj =document.createElement('option')
                      optObj.innerHTML = '앨범을 선택해주세요';
                      album.appendChild(optObj);
                      $(r).each(function(idx, item) {
                          $(album).append('<option value='+item.id+'>'+item.album_name+'</option>');
                      });
                      album.disabled = false;
                  }
            }
        });
}

function getCheckedCheckboxes(selector) {
	var ret = [];
	var checkboxes = $(selector);
        $.each(checkboxes, function(idx, item) {
            if(item.checked)
                ret.push(item);
        });
		return ret;
}

var Mymusic = {
	selector: 'input[type:checkbox].musics',
	form : {},
	removeFormAction :'/mymusic/remove',
	init: function(){
		if(document.getElementById("downloadForm")) {
            Mymusic.form = document.getElementById("downloadForm");
        } 
    },
	
	remove : function(checkAgain) {
		if(getCheckedCheckboxes(this.selector).length < 1) {
			alert('선택한 파일이 없습니다');
			return false;
		}
		if(checkAgain == undefined && !confirm('선택한 파일을 삭제하시겠습니까?')) {
			return false;
		}
		
        this.form.action = this.removeFormAction;
        this.form.submit();
	},
	
	removeAll : function() {
		if (!confirm('전체 파일을 삭제하시겠습니까?')) {
			return false;
		}
		this.selectAll(this.selector);
		this.remove(false);
	},
	
	downloadAll : function() {
        /*  고른 파일만 다운로드 하기
	    var files = [];
	    var checkboxes = $(this.selector);
	    $.each(checkboxes, function(idx, item){
	        files.push(item);
	    });
	    this.download(files);
        */
        $.ajax({
            url : '/mymusic/getAllDownloadables',
            dataType : 'json',
            success : function(r) {
                var downloads = '';
                $.each(r, function(idx, item) {
                    if(idx == 0) {
                       var seperator = '';
                    } else {
                       var seperator = '&';
                    }
                    downloads += seperator+'downloads[]='+item.id;
                });
                DownloadComponent.queue = downloads;
                DownloadComponent.startDownload.apply(DownloadComponent);
            },

            error : function() {

            }
            
        });
	},
	
	download : function (files) {
	    if(files == undefined) {
	        var files = getCheckedCheckboxes(this.selector);
	    }
	    if(files.length == 0) {
	        alert("선택된 파일이 없습니다");
	        return false;
	    }
	    DownloadComponent.queue = files;
	    DownloadComponent.startDownload();
	}, 
	
	selectAll : function() {
		var selector = this.selector;
        $.each($(selector), function(idx, item) {
            item.checked = true;
        });		
	}
	
};

var Basket = {
    selector : 'input[type:checkbox].musics',
    form : {},
	orderFormAction : '/order/doOrder',
	removeFormAction : '/basket/remove',
	
    remove : Mymusic.remove,
    removeAll : Mymusic.removeAll,
    init : function()
    {
        if(document.getElementById("basketForm")) {
            Basket.form = document.getElementById("basketForm");
        }
    },
    
    order : function() {
		Basket.form.action = Basket.orderFormAction;
        Basket.form.submit();
    },
    
    orderAll : function() {
        $.ajax({
            type : 'get',
            url : '/basket/onOrderAll' ,
            dataType : 'json',
            success : function(r) {
                var str = '';
                $.each(r, function(idx, item) {
                    str += '<input type="hidden" name="goods_id[]" value="'+item.goods_id+'">';
                });
                Basket.form.innerHTML += str;
                Basket.order.apply(Basket);
            },
            error : function() {

            }
        });
    },
    
    selectAll : Mymusic.selectAll,

    add : function(goods_id) {
        $.ajax({
            url : '/basket/addJSON/'+goods_id,
            type : 'get',
            dataType : 'json',
            success : function(r) {
                if(r.status) {
                } else {
                    alert('이미 음원 찜리스트에 담겨 있습니다'); 
                }
                Client.popup.open('/basket');
            },
            error : function() {
            }
        });
    },
    
    showAlbum : function(musics_id, issued, artists_id) {
        var year = issued.match(/^([0-9]{4})/)[0];
        window.interval = window.setInterval(function() {
            if(!window.opener) {
                window.opener = window.open('/');    
            }

            if(window.opener.getMovieName('ygmusic')) {
                var flash = window.opener.getMovieName('ygmusic');
                window.clearInterval(window.interval);
                flash.showthisalbum(musics_id, year, artists_id);
            }
        }, 100);
    }
};

var DownloadComponent = {
	queue : {},
	
	init : function() {
		window.Enc = "26b79ifNDNFlCmy4nfXwKk1kVawYW2nUOOdOhx+QnFkMZaxzy9E02+lweLiwNXKE634S3LtT+kwnvDXX+wTYnYb14uzdhP7N9K0W26VEdx1+Y0DJLb4JqWeklFJiS4la1jzBhUKnSroqbxHHC5IC5VmoIj6D8a4+4FUbshbSFePmbaG07gIaK5g2DgQT73LU2OIFyA+onKmynGSsV/46vaKQHXHLPAJZpQHk1q49LuL422eAd0d1d1Ms5laI45QNPZEfHoLr83zDHWVvCBXG0ejreSLQEY5TNU60Iz9XQLc=";
		window.InnoFD_Cab = "/innofd/InnoFD5.cab";
		window.OnInnoFDLoad = Basket.onLoad;
		window.LoadInnoFD(450, 150);
	},
	
	onLoad : function() {
	},
	
	startDownload : function() {
        document.InnoFD.RemoveAllFiles();
		$.ajax({
                url : '/mymusic/download/setQueue',
                type : 'post',
                data : DownloadComponent.queue,
                dataType : 'json',
                success : function(r) {
					if(!r.list || r.list.length == 0) {
						alert('다운 받으실 수 있는 파일이 없습니다.');
						return;
					}
					$.each(r.list, function(index, item) {
                        if(item.server == 'web') {
                            var url = "http://www.yg-music.net/download/doDownload/"+item.url;
                        } else {
                            var url = "http://218.232.95.26/music/download.php?q="+item.url
                        }
						document.InnoFD.AppendFile(url, item.orig_name, item.size);

					});
                    document.InnoFD.ShowFileOpen = true;
                    document.InnoFD.StartDownload();
                },
                error : function() {
                    alert('오류가 발생했습니다. 다시시도해주세요.');
                }
                });
	},
	
	onEndDownload : function() {
		window.location.reload();
	},
	
	browserCheck : function() {
        if (!/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
			alert('죄송합니다. 다운로드 서비스는 인터넷 익스플로러에서만 지원됩니다.');
			return false;
		}
        return true
	}
};

var ElcoLib = {
	/**
	 * php의 number_format과 동일한 역할
	 * http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
	 * @param {Object} number
	 * @param {Object} decimals
	 * @param {Object} dec_point
	 * @param {Object} thousands_sep
	 */
	number_format: function(number, decimals, dec_point, thousands_sep){
		var n = number, prec = decimals;
		
		var toFixedFix = function(n, prec){
			var k = Math.pow(10, prec);
			return (Math.round(n * k) / k).toString();
		};
		
		n = !isFinite(+n) ? 0 : +n;
		prec = !isFinite(+prec) ? 0 : Math.abs(prec);
		var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
		var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
		
		var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
		var abs = toFixedFix(Math.abs(n), prec);
		var _, i;
		
		if (abs >= 1000) {
			_ = abs.split(/\D/);
			i = _[0].length % 3 || 3;
			
			_[0] = s.slice(0, i + (n < 0)) +
			_[0].slice(i).replace(/(\d{3})/g, sep + '$1');
			s = _.join(dec);
		}
		else {
			s = s.replace('.', dec);
		}
		
		var decPos = s.indexOf(dec);
		if (prec >= 1 && decPos !== -1 && (s.length - decPos - 1) < prec) {
			s += new Array(prec - (s.length - decPos - 1)).join(0) + '0';
		}
		else 
			if (prec >= 1 && decPos === -1) {
				s += dec + new Array(prec).join(0) + '0';
			}
		return s;
	}
}

var Payment = {
	method : {
		change : function(obj) {
			document.getElementById('pay_method').value = obj.value;
		}
	}
};

function toggleCheckBoxes(checkbox, check)
{
	if(typeof checkbox == 'object') {	
		var className = checkbox.className;
		var checkboxes = $('input[type:checkbox].'+className.replace(' ', '.'));
	} else {
		var checkboxes = $(checkbox);
	}
	$.each(checkboxes, function(idx, item) {
		if(check == undefined)
			item.checked = !item.checked;
		else 
			item.checked = check;
	});
}


var Manager = {
    Order : {
        changeDownloadCount : function(obj) {
          var matched = obj.name.match(/count\[([0-9]*)\]/);
          var download_id = matched[1];
          $.ajax({
            url : "/manager/order/changeDownload/"+download_id,
            type : 'post',
            dataType : 'json',
            data : "count="+obj.value,
            success : function(r) {
                statusAlert(r.message);        
            },
            error: function() {
                statusAlert('실패했습니다. 다시시도해 주세요');
            }
          });
        }
    },
    File : {
        onMusicTypeSet : function(select) {
             if(window.swfu.source) {
                 window.location.reload();    
             }
            if(select.value == 'PACKAGE' || select.value == 'INST') {
                window.swfu.source = getSourceUploader_dataserver();
            } else {
                window.swfu.source = getSourceUploader_webserver();
            }
            Manager.Music.showUploadFields();
        },
        remove : function(hiddenField, anchor) {
            var val = hiddenField.value;
            hiddenField.value = 0;
            var input = $(anchor).parents('td').children('input[type=text]')[0];
            input.value = '';
            if(val > 0) {
		        $.ajax({
                     url : '/manager/upload/remove/'+val,
                     type : 'get',
                     dataType : 'json',
                     error : function() {
                     },
                     success : function(r) {
                     }
                });
            }
            return false;
        }
           },
    onRemove : function(anchorObj){
        var link = anchorObj.href;
        if(confirm('삭제하시겠습니까?')) {
            return true;
        }
        return false;
    },
    popup : {
        open :function(anchorObj, name, size, options) {
            if(name == undefined) name = 'manager_popup'; 
            if(size == undefined) {
                   var size = [50, 50];
            }

            if(typeof anchorObj == 'Object') {
                var addr = anchorObj.href;
            } else {
                var addr = anchorObj;
            }

            if(!options) {
                    managerPopup = window.open(addr, name, "scrollbars=yes, width="+size[0]+", height="+size[1]);
                } else {
                    managerPopup = window.open(addr, name, options+", width="+size[0]+", height="+size[1]);
                }
            window.setTimeout(function() {
                if(!managerPopup) {
                    alert('팝업차단이 작동하고 있습니다. 해제해주세요');
                } else {
                    managerPopup.focus();
                }
            }, 500);
            return false;
        },

        resize : function(width, height) {
            var Browser = new Object();
            Browser.isIE = (navigator.userAgent.toLowerCase().indexOf("msie")!=-1);
            Browser.isIE_SV1 = (navigator.userAgent.toLowerCase().indexOf("sv1")!=-1);
            Browser.isIE_SV2 = (navigator.userAgent.toLowerCase().indexOf("sv2")!=-1);
            Browser.isIE_7 = (navigator.userAgent.toLowerCase().indexOf("msie 7")!=-1);
            Browser.isIE_8 = (navigator.userAgent.toLowerCase().indexOf("msie 8")!=-1);
            Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox/2")!=-1);
            Browser.isFirefox3 = (navigator.userAgent.toLowerCase().indexOf("firefox/3")!=-1);
            Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari")!=-1);
            Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1);
            Browser.isNetscape = (navigator.userAgent.toLowerCase().indexOf("netscape")!=-1);
            Browser.isEtc = (navigator.userAgent.toLowerCase().indexOf("gecko")!=-1 && navigator.userAgent.toLowerCase().indexOf("firefox")==-1 && navigator.userAgent.toLowerCase().indexOf("netscape")==-1 );

            var h=18;
            if(!height) {
                var popHeight = $('body')[0].offsetHeight+34;
            } else {
                var popHeight = height + 34;
            }
            $('body')[0].style.height = height-5+'px';
            width = width + 30;
            if (Browser.isIE_SV1)         { h += 14; } // h = 14; 
            else if(Browser.isIE_7)       { h += 48; } // h = 18; // h+= 48;
            else if(Browser.isIE_8)       { h += 45; } // h = 18; // h+= 48;
            else if(Browser.isEtc)        { h += 22; }
            else if(Browser.isFirefox)    { h += 32; }
            else if(Browser.isFirefox3)   { h += 52; }
            else if(Browser.isNetscape)   { h += -2; }
            else if(Browser.isOpera)  { h += 26; }
            else { h = h; }

            window.resizeTo(width, popHeight + h);
            if(Browser.isIE) { /*IE 6,7에서 양쪽 제대로 못맞춰주는 버그 Fix*/
                $('body').hide();
                $('body').show();
            }
         }
    },

    Music : {
        showUploadFields : function() {
            $('tr.uploads').show();

        },

        Track : {
            onclick : function(el) {
                $(el).children('span').toggle();
                $(el).children('form').toggle();
                $(el).children('form').children('input[type=text]')[0].focus();
            },
            send : function(f) {
                var self = this;
		        $.ajax({
                     url : f.action,
                     type : f.method,
                     data : $(f).serialize(),
                     dataType : 'html',
                     error : function() {
                     },
                     success : function(r) {
                         $(f).toggle();
                         var span = $(f).parent('td').children('span');
                         span[0].innerHTML = r;
                         span.toggle();
                     }
                     
                });
                return false;
            }
        }
    }
}


var Album = {
        UI : {
            tempTable : null,
            Form : {
                getForm : function() {
                   return $('form.comment');
                },
                getFormElements : function() {
                    return this.getForm()[0].elements;
                },
                disable : function() {
                    this._setDisable(true);
                },
                enable : function() {
                    this.clear();
                    this._setDisable(false);
                },
                _setDisable : function(bStatus) {
                    $(this.getFormElements()).each(function(idx, item){
                        item.disable = bStatus;
                    });
                },
                clear : function() {
                    var f = this.getForm();
                    $(this.getFormElements()).each(function(idx, item){
                        item.value = '';
                        item.innerHTML = '';
                    });
                }
            },
            CommentList : {
                tempTable : '',
                insert : function(content) {
                    tempTable = this.getTempTable();
                    tempTable.innerHTML = content;
                    var newElement = tempTable.getElementsByTagName('tr')[0];
                    var tr = this.getReplyTable()[0].insertRow(0);
                    tr.innerHTML = newElement.innerHTML;
                },
                    getTempTable : function() {
                        if(this.tempTable) {
                            this.tempTable.innerHTML = '';
                            return this.tempTable;
                        }
                        var table = document.createElement('table');
                        $(table).hide();
                        this.tempTable = table;
                        return this.tempTable;
                    },

                    getReplyTable : function() {
                        return $('#replytable');
                    },

                    addPaginationEvent : function() {
                        var container = this.getReplyContent().children('div.paging');
                        container.children('a').each(function(idx, item) {
                            item.onclick = function() {
                                Album.loadComment(this);
                                return false;   
                            };
                            
                        });

                        container.children('span').each(function(idx, item) {
                            item.onclick = function() {
                                Album.loadComment(this);
                                return false;   
                            };
                            
                        });
                    },
                    setReplyContent : function(result) {
                        this.getReplyContent()[0].innerHTML = result;
                        window.setTimeout('Album.UI.CommentList.addPaginationEvent.apply(Album.UI.CommentList)', 100);
                        this.getReplyContent().show();
                    },

                    getReplyContent: function() {
                        return $('#replycontent');
                    },

                    remove : function(item) {
                    }
              },

            Star : {
                on : function() {
                    
                },

                off : function() {

                },

                fix : function() {


                }
            }
        },

        loadComment : function() {
                var type = 'get';
                var data = '';

                if((typeof arguments[0]) == 'object') {
                   if(arguments[0].tagName == 'A') {
                       url = arguments[0].href;
				   } else if(arguments[0].tagName == 'SPAN') {
					   url = arguments[0].id;
                   } else if(arguments[0].tagName == 'FORM') {
                       url = arguments[0].action;
					   url1 = '/comment/listing/'+arguments[0].elements.albums_id.value;
					   type = arguments[0].method;
                       data = $(arguments[0]).serialize();

						$.ajax({
									url : url,
									type : type,
									dataType : 'json',
									data : data,
									success : function(r) {
										$('#replycontent')[0].innerHTML = "로딩중...";
										cmt_req = getXMLHttpRequest();
										cmt_req.onreadystatechange = CommentResult;
										cmt_req.open("GET", url1, true);
										cmt_req.send(null);
									},
									error : function() {
										alert('오류가 발생했습니다. 다시시도해주세요.');
									}
						});
						return false;
                   }
                } else {
                    url = '/comment/listing/'+arguments[0];
                }

				$('#replycontent')[0].innerHTML = "로딩중...";
				cmt_req = getXMLHttpRequest();
				cmt_req.onreadystatechange = CommentResult;
				cmt_req.open("GET", url, true);
				cmt_req.send(null);

				return false;
        },
        checkCommentLength : function(textarea, event) {
			if(byte_length(textarea.value) > 50){
				alert('50바이트를 초과했습니다');
				textarea.value = cut_str_byte(textarea.value , 50);
				return false;
			}
			return true;
        },

        sendComment : function(form) {
			if(jQuery.trim(form.star.value) == '0') {
                alert('별점을 선택해주세요');
                return false;
            }
            if(!jQuery.trim(form.comment.value) || jQuery.trim(form.comment.value) == '앨범에 대한 여러분의 의견을 들려주세요. (최대 70자)' || jQuery.trim(form.comment.value) == '앨범에 대한 여러분의 의견을 들려주세요. (최대 50바이트)') {
                alert('댓글을 입력해주세요');
                form.comment.focus();
                return false;
            }

			if(document.getElementById('btn_comment')) document.getElementById('btn_comment').style.display = 'none';
			if(document.getElementById('btn_comment_proc')) document.getElementById('btn_comment_proc').style.display = '';

            this.UI.Form.disable();
            var albumID = form.elements.albums_id.value;
            this.loadComment(form);
            return false;
        },

        removeComment : function(anchor) {
            this.loadComment(anchor);
            return false;
        }
    };
var Client = {
    onRemove : Manager.onRemove,
    popup : Manager.popup,
    onAlbumSelect : Album.loadComment
}

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

var Order = {};
Order.add = function(goods_id) {
    Client.popup.open('/order/doOrder/'+goods_id);
};

Order.addAlbum = function(goods_id) {
    Client.popup.open('/order/doOrder/'+goods_id);
};

function chk_byte(chr){
	var c = escape(chr);
	if(c.length == 1) return 1;
	else if(c.indexOf("%u") != -1) return 2;
	else if(c.indexOf("%") != -1) return c.length/3;
}

function cut_str_byte(str , limit_length){
	var byte_size = 0;
	for(var i=0; i<str.length; i++){
		byte_size += chk_byte(str.charAt(i));
		if(byte_size > limit_length) break;
	}
	return str.substr(0 , i);
}

function byte_length(str){
	var resultSize = 0;
	if (str == null) return 0;
	for(var i=0; i<str.length; i++) resultSize += chk_byte(str.charAt(i));
	return resultSize;
}

function chk_byte_length(obj , limit_length){
	if(byte_length(obj.value) > limit_length){
		alert(limit_length + '바이트를 초과했습니다');
		obj.value = cut_str_byte(obj.value , limit_length);
		return false;
	}
	return true;
}