/*
 * need jquery
 * by zy
 */

var upload = {
    uploadInfo: null,
    bar: null,
    text: null,
    content: null,
    contextPath: null,
    width: null,
    height: null,
    SubmitId:'Submit2',
    refreshProgress: function(){
        var self = this;
        self.getUploadInfo(self.updateProgress);
    },
    
    updateProgress: function(){
        var self = this;
        var uploadInfo = self.uploadInfo;
        var lthalf = true;
        if (uploadInfo.inProgress) {
            //document.getElementById('uploadbutton').disabled = true;
            
            var fileIndex = uploadInfo.fileIndex;
            
            var progressPercent = Math.ceil((uploadInfo.bytesRead / uploadInfo.totalSize) * 100);
            if (lthalf && progressPercent > 90) {
                //alert(self.bar);
                self.bar.fadeTo("slow", 0.33);
            }
            //alert(progressPercent +" "+ fileIndex+" "+uploadInfo.bytesRead+" "+uploadInfo.totalSize+" text:"+ self.text );
            self.text.html('<span class="baifenbi">' + progressPercent + '%</span>');
            
            self.content.width(parseInt(progressPercent * 1.5) + 'px');
            
            window.setTimeout("upload.refreshProgress()", 1);
        }
        return true;
    },
    startMusicProgress: function(bar, text, content, contextPath, it){
		
        // alert("aaa");
        //  document.getElementById("savemusic").disabled=true;
		
        var filestr = it.value.substring(it.value.lastIndexOf("\\") + 1, it.value.length);
       
		filename = filestr.substring(0, filestr.indexOf("."));
        
		filetype = filestr.substring(filestr.indexOf(".") + 1);
       
        if (filetype.toLowerCase() !== 'mp3' && filetype.toLowerCase() !== 'wma' && filetype.toLowerCase() !== 'wav' && filetype.toLowerCase() !== 'midi') {
            alert("file type is error!");
            return;
        }
		//alert("fileName::"+filename);
        $("#musicname").val(filename);
        $("#savemusicing").show();
        $("#savemusicing").attr("disabled", true);
        $("#savemusic").hide();
        $("#loading").show();
        this.startMusicProgress1(bar, text, content, contextPath);
    },
    startMusicProgress1: function(bar, text, content, contextPath){
        var self = this;
        self.bar = $("#" + bar);
        self.text = $("#" + text);
        self.content = $("#" + content);
        var photonamenull = false;
        self.text.html('<span class="baifenbi">0%</span>');
        $("#rightview > li > input").each(function(){
            if (!$.trim(this.value)) {
                photonamenull = true;
                alert(3);
                this.focus();
            }
        });
        if (photonamenull) 
            return;
        
        self.contextPath = contextPath;
        //self.width       = $("#w").val();
        //self.height      = $("#h").val();	
        self.bar.show("slow");
        with (document.getElementById('fileUploadMusicFrom')) {
            var hasValue = false;
            $(":file").each(function(i){
                if (this.value) {
                    hasValue = true;
                }
            });
            if (hasValue) {
                submit();
                window.setTimeout("upload.refreshProgress()", 1);
            }
        }
    },
	
    startProgress: function(bar, text, content, contextPath){
        var self = this;
        self.bar = $("#" + bar);
        self.text = $("#" + text);
        self.content = $("#" + content);
        var photonamenull = false;
        self.text.html('<span class="baifenbi">0%</span>');
        $("#rightview > li > input").each(function(){
            if (!$.trim(this.value)) {
                photonamenull = true;
                alert(3);
                this.focus();
            }
        });
        if (photonamenull) 
            return;
        self.contextPath = contextPath;
        //self.width       = $("#w").val();
        //self.height      = $("#h").val();	
        self.bar.show("slow");
        with (document.getElementById('fileUploadFrom')) {
            var hasValue = false;
            $(":file").each(function(i){
                if (this.value) {
                    hasValue = true;
                }
            });
            if (hasValue) {
				makeDisable("Submit2","true");
                submit();
                window.setTimeout("upload.refreshProgress()", 1);
            }
        }
    },
	 
     startProgress2: function(fileId,thisFormId,allSubmitId){
	 var file = document.getElementById(fileId);
	 var flag=true;
	 if(file.value==""||file.value==null){
	 	alert("请选择文件再上传");return false;
	 }
	 document.getElementById(thisFormId).submit();
	 makeDisable(allSubmitId,"true");
    },
    getUploadInfo: function(fn){
        var self = this;
        //alert( self.contextPath+"/movoupload!uploadInfo.do");        
        $.ajax({
            type: "GET",
            data: "asdf=" + Math.random(),
            url: self.contextPath + "/movoupload!uploadInfo.do",
            success: function(res){
                if (res != "") {
                    eval("upload.uploadInfo =" + res);
                    //alert(self.uploadInfo+" "+res);
                    fn.call(self);
                }
                else {
                    window.setTimeout("upload.refreshProgress()", 1);
                }
            }
        });
    },
    uploadError: function(error){
        alert(error);
        window.close();
    },
    uploadSizeError: function(error){
        alert(error);
        window.close();
    },
    uploadTypeError: function(error){
        alert(error);
        window.close();
    },
    uploadBlogCompleted: function(fileUrlStr, fileSizeStr, filename){
        //alert(fileUrlStr+ " ss :"+fileSizeStr);
        var self = this;
        document.getElementById('fileUploadFrom').reset();
        fileUrlStr = fileUrlStr.replace(":", "");
        fileSizeStr = fileSizeStr.replace(":", "");
        //alert("urls="+fileUrlStr+"&names="+filename+"&sizes="+fileSizeStr+"&suserid="+$("#suserid").html()+"&mphotoimages.photoset.photosetid="+$("#psid").val());
        
        $.ajax({
            type: "post",
            data: "urls=" + fileUrlStr + "&names=" + filename + "&sizes=" + fileSizeStr + "&suserid=" + $("#suserid").html() + "&mphotoimages.photoset.photosetid=" + $("#psid").val(),
            url: maincontext + "/adminphoto!savePhotos.do",
            success: function(res){
                //alert(res+" "+$("#articleContext"));   		  	
                var context = document.getElementById("articleContext").value;
                context = fileUrlStr;
                __Attachement(context);
                document.getElementById("articleContext").value = __EditorWindow.document.body.innerHTML;
              // document.getElementById('upimg').style.display = 'none';
            }
        });
    },
	uploadCompleted_yedian : function(fileUrlStr, fileSizeStr){
        var self = this;
        self.text.html('<span class="baifenbi">100%</span>');
        self.content.width('150px');
        document.getElementById('fileUploadFrom').reset();
        savephoto_yedian(fileUrlStr, fileSizeStr);
    },
    uploadCompleted: function(fileUrlStr, fileSizeStr){
        var self = this;
        self.text.html('<span class="baifenbi">100%</span>');
        self.content.width('150px');
        document.getElementById('fileUploadFrom').reset();
        savephoto(fileUrlStr, fileSizeStr);
    },
    uploadUserMusic: function(fileUrlStr, fileSizeStr, timelength){
        var self = this;
        $("#musicurl").val(fileUrlStr);
        $("#musicsize").val(fileSizeStr);
        $("#musictime").val(timelength);
        $("#savemusicing").hide();
        $("#savemusic").show();
        self.text.html('<span class="baifenbi">100%</span>');
        self.content.width('150px');
        $("#loading").hide();
        
        //$("savemusic").disabled=false;
        document.getElementById("savemusic").disabled = false;
        //	alert("upload music success"+fileUrlStr+" filesize:"+fileSizeStr);
    },
    uploadUserPhoto: function(fileUrlStr, fileSizeStr){
        //alert(fileUrlStr+" :  "+fileSizeStr);	
		makeDisable("Submit2",false);
        $("#userphotoimg").attr("src", fileUrlStr);
        $("#coverurl").attr("value", fileUrlStr);
        $("#userphotoid").val(fileUrlStr);
	    alert('UPLOAD SUCCESS!');
    },
    /*uploadCompassCompleted : function(fileUrl){  
     var self   = this;
     window.close();
     window.opener.document.getElementById("image").value = fileUrl;
     window.opener.document.getElementById("imgPreview").innerHTML="<img id='"+fileUrl+"' src='"+fileUrl+"'/>";
     },*/
	/**
	 * 通用的上传后显示图片控件。
	 * @param {Object} fileUrlStr
	 * @param {Object} fileSizeStr
	 * @param {Object} whichIdShow(用哪个地方显示图片)
	 * @author by zlj
	 */
	uploadImage:function (fileUrlStr,fileSizeStr,whichIdShow){
		document.getElementById("Submit2").disabled=false;
		$("#"+whichIdShow).attr("value", fileUrlStr);
		$("#fileSize").attr("value",fileSizeStr);
		var whereToShow = document.getElementById("img_"+whichIdShow);
		if(whereToShow!=null){
			whereToShow.src=fileUrlStr;
			whereToShow.width="100";
			whereToShow.height="100";
		}
	},
    uploadMusicCompleted: function(fileUrl){
        var self = this;
        window.close();
        window.opener.__EditorWindow.document.body.innerHTML = window.opener.__EditorWindow.document.body.innerHTML +
        "<P><embed src='" +
        fileUrl +
        "' width='300' height='69' type='application/x-mplayer2' loop='-1' showcontrols='1' ShowDisplay='0' ShowStatusBar='1' autostart='0'></EMBED></P>";
        window.opener.document.getElementById("content").value = window.opener.__EditorWindow.document.body.innerHTML;
    },
    uploadVidioCompleted: function(fileUrl){
        var self = this;
        window.close();
        window.opener.__EditorWindow.document.body.innerHTML = window.opener.__EditorWindow.document.body.innerHTML +
        "<P><embed style='filter:Alpha(opacity=10,finishOpacity=100,style=2); WIDTH: 300px; HEIGHT: 300px' src='" +
        fileUrl +
        "' width='300' height='300' type='audio/mpeg' volume='100' loop='true' autostart='0' showstatusbar='1'></EMBED></P>";
        window.opener.document.getElementById("content").value = window.opener.__EditorWindow.document.body.innerHTML;
    }
}

var test = function(){
    var tagstr = $.trim($("#tags").val());
    var exp = /\w+/g;
    var arr = tagstr.replace(/(\w+|[^\x00-\xff]+)/g, "tags=$1");
    alert(arr);
    var tags = null;
}
var savephoto_yedian = function(filesStr, fileSizeStr){
    if (!filesStr) {
        alert("upload img error!");
        return;
    };
    var files = filesStr.split(":");
    var filesizes = fileSizeStr.split(":");
    var photos = new Array();
    $("#rightview > li > input").each(function(i){
        photos.push("urls=" + files[i] + "&names=" + this.value + "&sizes=" + filesizes[i]);
    });
    var tagstr = $.trim($("#tags").val());
	//if(tagstr==null)
	
	//alert("tagstr::"+tagstr);
    var tags = tagstr.match(/\w+|[^\x00-\xff]+/g);
    if (tags) {
        for (var i = 0; i < tags.length; i++) {
            photos.push("tags=" + tags[i]);
        }
    }
  // alert(photos.join("&"));
	//alert($("#tags").val());
    $.ajax({
        type: "post",
        data: photos.join("&") + "&suserid=" + $("#suserid").html() +"&tags='"+$("#tags").val()+ "'&mphotoimages.photoset.photosetid=" + $("#psid").val(),
        url: maincontext + "/adminphoto!savePhotos.do",
        success: function(res){
            if (res.indexOf("success") != -1) {
                location.href = maincontext + "/photo!showphoto.do?toStore=yes&psid="+$("#psid").val()+"&suserid=" + $("#suserid").html() + "&photoimages.photoimagesid=" + res.split('&')[1];
            }
            else {
                alert(res);
            }
        }
    });
}

var savephoto = function(filesStr, fileSizeStr){
    if (!filesStr) {
        alert("upload img error!");
        return;
    };
    var files = filesStr.split(":");
    var filesizes = fileSizeStr.split(":");
    var photos = new Array();
    $("#rightview > li > input").each(function(i){
        photos.push("urls=" + files[i] + "&names=" + this.value + "&sizes=" + filesizes[i]);
    });
    var tagstr = $.trim($("#tags").val());
    var tags = tagstr.match(/\w+|[^\x00-\xff]+/g);
    if (tags) {
        for (var i = 0; i < tags.length; i++) {
            photos.push("tags=" + tags[i]);
        }
    }
   // alert(photos.join("&"));
    $.ajax({
        type: "post",
        data: photos.join("&") + "&suserid=" + $("#suserid").html() + "&mphotoimages.photoset.photosetid=" + $("#psid").val(),//
        url: maincontext + "/adminphoto!savePhotos.do",
        success: function(res){
            if (res.indexOf("success") != -1) {
                location.href = maincontext + "/photo!showphoto.do?suserid=" + $("#suserid").html() + "&photoimages.photoimagesid=" + res.split('&')[1];
            }
            else {
                alert(res);
            }
        }
    });
}

var rightview = function(){
    $("#rightview").empty();
    $("#filelist > li > input").each(function(i){
        if (this.value) {
            var filename = this.value.substring(this.value.lastIndexOf("\\") + 1, this.value.length);
            filename = filename.substring(0, filename.indexOf("."));
          if(document.getElementById("storeImageId")!=null)
		    $("#rightview").append("<li><img src='file:///" + this.value.replace(":", "|").replace(/\\/g, "/") + "' /><br /><input type='text' style=\"border:1px solid #ccc;background:#fff;line-height:19px;color:#000;margin-top:5px;\"  value='" + filename + "' size='15' /></li>");
          else
		  $("#rightview").append("<li><img src='file:///" + this.value.replace(":", "|").replace(/\\/g, "/") + "' /><br /><input type='text'   value='" + filename + "' size='15' /></li>");
		}
    });
}
var increasefile = function(){
    var size = $("#filelist > li").size() + 1;
    if (size <= 6) 
        $("#filelist").append('<li id="li' + size + '">' + size + ':<input type="file" name="files" onchange="rightview(this);" />&nbsp;&nbsp;<img src="http://images.movo.tv/movo_tv/manage/images/icon_del.gif" onclick="decreasefile(this);" /></li>');
    else 
        alert('too many');
}

var decreasefile = function(it){
    var size = $("#filelist > li").size();
    if (size == 1) 
        return;
    var id = $($(it).parent().get(0)).attr("id");
    $("#" + id).replaceWith("");
    rightview();
}

var selectexitedtag = function(exitedTagStr){
    var tagstr = $.trim($("#tags").val());
    var tags = tagstr.match(/\w+|[^\x00-\xff]+/g);
    var prefix = null;
    var issame = false;
    if (tags) {
        for (var i = 0; i < tags.length; i++) {
            if (tags[i] && tags[i] == exitedTagStr) 
                issame = true;
        }
        prefix = $("#tags").val() + ",";
    }
    else {
        prefix = "";
    }
    
    if (!issame) {
        $("#tags").val(prefix + exitedTagStr);
    }
}

var showMoreTags = function(){
    document.getElementById("mytags").style.height = "";
    document.getElementById("mytags").style.overflow = "";
}
var maincontext = "/movo";
var makeDisable =function (who,flag){
	 var storeUpFlag=document.getElementById(who);
	 if(storeUpFlag!=null)
	  storeUpFlag.disabled =flag;	
		
	 }
