var PKCard = {
    images:new Array(),
    getMedias:function(){
        PKToonWeb.Container.unset("preObj");
        $('picture_list').innerHTML = "&nbsp;";
        $('op_for_pic').hide();
        $('op').show();

        $('img_xhk1').setStyle({
            width:'140px',
            height:'39px'
        });
        $('img_xdh2').setStyle({
            width:'140px',
            height:'39px'
        });
        $("sel_media").selectedIndex = 0;
        $("search_content").value = "";
        $("card_tip").style.top = "106px";
        $("card_tip").style.left = "653px";
        $("card_tip").show();
        PKUtil.retrievePage('/card/media_list/-1/1', 'media_list');
    },
    getPictures:function(){
        PKToonWeb.Container.unset("preObj");
        $('media_list').innerHTML = "&nbsp;";
        $('op').hide();
        $('op_for_pic').show();

        $('img_xhk2').setStyle({
            width:'140px',
            height:'39px'
        });
        $('img_xdh1').setStyle({
            width:'140px',
            height:'39px'
        });
        $("sel_pic").selectedIndex = 0;
        $("card_tip").style.top = "106px";
        $("card_tip").style.left = "653px";
        $("card_tip").show();
        PKUtil.retrievePage('/card/card_picture_list/-1/1', 'picture_list');
    },
    changePicCategory:function(categoryId){
        $('pic_category_name').value = $('sel_pic').options[$('sel_pic').selectedIndex].text;
        PKUtil.retrievePage("/card/card_picture_list/"+categoryId+"/1", "picture_list");
    },
    changeMediaCategory:function(categoryId){
        PKUtil.retrievePage("/card/media_list/"+categoryId+"/1", "media_list");
    },
    clickMedia:function(obj,id,media_path){
        try{
            var preObj = PKToonWeb.Container.get("preObj");
            if(preObj != undefined && preObj != null && $(preObj).up('div') != null){
                $(preObj).up('div').setStyle({
                    backgroundColor:'#FFF'
                });
            }
            $(obj).up('div').setStyle({
                backgroundColor:'#FFEEC2'
            });
            PKToonWeb.Container.set("preObj",obj);
        }catch(e){}
        pktoonPlayer("/medias/flash/flvplayer.swf",media_path, "flash_media", "240", "195", "uuid", "lid");
        $("m_id").value = id;
        PKToonWeb.Container.set("mediaObj",media_path);
    },
    clickPicture:function(obj,index,picThumb,bg_url,name){
        try{
            var preObj = PKToonWeb.Container.get("preObj");
            if(preObj != undefined && preObj != null && $(preObj).up('div') != null){
                $(preObj).up('div').setStyle({
                    backgroundColor:'#FFF'
                });
            }
            $(obj).up('div').setStyle({
                backgroundColor:'#FFEEC2'
            });
            PKToonWeb.Container.set("preObj",obj);
        }catch(e){}
        $('card_picture').setStyle({
            backgroundImage:"url("+PKCard.images[index].src+")"
        });
        $("picture_path").value = PKCard.images[index].src ;
        PKToonWeb.Container.set("pic_thumb_path",picThumb);
        image_name = name;
        PKToonWeb.Container.set("bg_url",bg_url);
    },
    closeMediaList:function(){
        $('op').hide();
        $("card_tip").hide();
    },
    selectMedia:function(){
        var preObj = PKToonWeb.Container.get("preObj");
        if(preObj == undefined || preObj == null){
            alert(NativeText.get("select_media"));
            return false;
        }
        $('op').hide();
    },
    closePictureList:function(){
        $('op_for_pic').hide();
        $("card_tip").hide();
    },
    selectPicture:function(){
        var preObj = PKToonWeb.Container.get("preObj");
        if(preObj == undefined || preObj == null){
            alert(NativeText.get("select_card"));
            return false;
        }
        $('op_for_pic').hide();
    },
    onSearch:function(){
        if(!$F("search_content").blank())
            PKUtil.loadPage("/card/search_media/"+$F('sel_media')+"/1", "media_list","form1");
    },
    preview:function(url, width, height, loadingString){
        $('op_for_pic').hide();
        $("card_tip").hide();
        $('op').hide();
        var dlg = $('card_dialog');
        var bg = $('card_bg');
        try {
            var docWidth = document.viewport.getWidth();
            var docHeight = document.viewport.getHeight();
            dlg.style.display    = '';
            l = docWidth > width ? Math.floor((docWidth - width) / 2) : 0;
            t = docHeight > height ? Math.floor((docHeight - height) / 2) : 0;
            dlg.style.left = l + 'px';
            dlg.style.top = t + 'px';
            dlg.style.width	= width + 'px';
            dlg.style.height = height + 'px';

            //bg.setOpacity(0.8);
            bg.style.backgroundColor = "#403C31";
            bg.style.display        = '';
            bg.style.height        = document.viewport.getHeight()+ 94 + 'px';
            bg.style.width        = docWidth + 'px';
        }catch(e){}
        $('card_content').innerHTML = loadingString; 
        var p = PKUtil.authenticityToken() + "&picture_path="+$F("picture_path")+"&m_path="+PKToonWeb.Container.get("mediaObj")+"&title="+PKUtil.urlEncode($F('title'))+"&content="+PKUtil.urlEncode(PKCard.checkContent($('content'),170,4,40))+"&signed="+PKUtil.urlEncode($F('signed'));

        new Ajax.Request(url,
        {
            method: "post",
            postBody:p,
            onSuccess: function(rsp){
                if (rsp.status / 100 == 2){
                    $('card_content').innerHTML = "";
                    Element.insert('card_content', rsp.responseText);
                }else{
                    PKCard.closePreviewDialog();
                }
            },
            onFauilre: function(){
                PKCard.closePreviewDialog();
            }
        }
        );
    },
    buildCard:function(){
        try {
            var url = "/card/build";
            var params = PKUtil.authenticityToken()+"&image_id=" + image_id + "&m_id="+$F('m_id')+ "&picture_path="+$F("picture_path")+"&m_path="+PKToonWeb.Container.get("mediaObj")+"&title="+PKUtil.urlEncode($F('title'))+"&content="+PKUtil.urlEncode(PKCard.checkContent($('content'),170,4,40))+"&signed="+PKUtil.urlEncode($F('signed'))+"&pic_thumb_path="+PKToonWeb.Container.get("pic_thumb_path")+"&pic_category_name="+$F('pic_category_name')+"&u="+PKUtil.urlEncode(PKToonWeb.Container.get("bg_url")) + "&image_name=" +PKUtil.urlEncode(image_name) ;
            new Ajax.Request(url,
            {
                method: "post",
                postBody: params,
                onSuccess: function(rsp) {
                    var ret = rsp.responseText.evalJSON();
                    if (ret.result == 'true') {
                        window.location.href="/card/complete";
                    }else if(ret.result == 'false'){
                        PKCard.popupCardDialog("/user/sign_in", 702, 420, "");

                    }else{
                        alert(ret.result);
                    }
                },
                onFailure: function(rsp) {
                    PKCard.popupCardDialog("/user/sign_in", 702, 420, "");
                }
            }
            );
        } catch (ex) {}
    },
    popupCardDialog:function(url, width, height, loadingString){
        var dlg = $('popup_dialog');
        var bg = $('popup_bg');
        try {
            var docWidth = document.viewport.getWidth();
            var docHeight = document.viewport.getHeight();
            dlg.style.display    = '';
            l = docWidth > width ? Math.floor((docWidth - width) / 2) : 0;
            t = docHeight > height ? Math.floor((docHeight - height) / 2) : 0;
            dlg.style.left = l + 'px';
            dlg.style.top = t + 'px';
            dlg.style.width	= width + 'px';
            dlg.style.height = height + 'px';

            bg.setOpacity(0.8);
            bg.style.backgroundColor = "#101010";
            bg.style.display        = '';
            bg.style.height        = document.viewport.getHeight()+ 94 + 'px';
            bg.style.width        = docWidth+ 'px';
        }catch(e){}
        $('popup_content').innerHTML = loadingString;
        new Ajax.Request(url,
        {
            method: "get",
            onSuccess: function(rsp){
                if (rsp.status / 100 == 2){
                    $('popup_content').innerHTML = "";
                    Element.insert('popup_content', rsp.responseText);
                }else{
                    PKCard.closeCardDialog();
                }
            }
        }
        );
    },
    closePreviewDialog:function(){
        $('card_content').innerHTML = "";
        $('card_dialog').style.display    = 'none';
        $('card_bg').style.display        = 'none';
    },
    sendEmail:function(){
        PKCard.popupCardDialog("/card/send_email", 385, 454, "");
    },
    addEmailAddress:function(email){
        if (!email.blank()){
            if($('contact_list').value.match(email+";") == null)
                $('contact_list').value = $('contact_list').value + email +"; ";
        }
    },
    sendCard:function(){
        if($('contact_list').value.blank()){
            alert(NativeText.get("email_empty"));
            $('contact_list').focus();
            return false;
        }
        if(!PKCard.validateEmail($('contact_list').value)){
            alert(NativeText.get("email_invalid"));
            $('contact_list').focus();
            return false;
        }
        $('ljfs').hide();
        $('ljfshb').show();
        var url = "/card/send_email_core";
        var params = PKUtil.authenticityToken()+"&card_url="+ PKToonWeb.Container.get("card_url") +"&email_list="+$('contact_list').value;
        new Ajax.Request(url,{
            method:"post",
            postBody:params,
            onSuccess:function(rsp){
                var result =rsp.responseText;
                if(result.indexOf('cards') > -1){
                    alert(NativeText.get("send_email_success"));
                    PKCard.closeCardDialog();
                    $('contact_list').value = "";
                }else{
                    alert(result);
                    $('ljfshb').hide();
                    $('ljfs').show();
                }
            },
            onFailure:function(rsp){
                alert(rsp.responseText);
            }
        });
    },
    feedBack:function(){
        var p = PKUtil.authenticityToken()+"&title="+PKUtil.urlEncode($F('title'));
        var req = new Ajax.Request('/card/feed_back',{
            method:'post',
            postBody:p,
            onSuccess:function(rsp){
                location.href='/card/make';
            }
        });
    },
    closeCardDialog:function(){
        $('popup_content').innerHTML = "";
        $('popup_dialog').style.display    = 'none';
        $('popup_bg').style.display        = 'none';
    },
    checkContent:function(theTextArea,maxChars,maxLines,maxPerLine){
        var strContent = "";//有效内容
        var all_Num = 0;
        var strLineCounter = 1;//总行数
        var strCharCounter = 0;//每行字数
        var contents = theTextArea.value.split("");
        for (var i = 0; i < contents.length; i++)
        {
            if(all_Num > maxChars){
                alert("最多只能输入" + maxChars + "个字符");
                theTextArea.value = $('textContent').value;
                return false;
            }else if(strLineCounter > maxLines){
                alert("最多允许输入"+maxLines+"行内容");
                theTextArea.value = $('textContent').value;
                return false;
            }
            var strChar = contents[i];
            if (strChar == '\n')
            {
                if(strLineCounter < maxLines){
                    strContent += strChar
                }
                all_Num += 2;
                strCharCounter = 0;
                strLineCounter ++;
            }
            else if (strCharCounter >= maxPerLine)
            {
                if(!strChar.match(/[^\u4E00-\u9FA5]/g) || !strChar.match(/[^\uFF00-\uFFFF]/g)){
                    all_Num += 4;
                }else{
                    all_Num +=3;
                }
                if(strLineCounter == maxLines){
                    strContent += strChar
                }else{
                    strContent += "\n"+strChar
                }
                strLineCounter += 1;
                strCharCounter = 0;
            }else{
                if(!strChar.match(/[^\u4E00-\u9FA5]/g) || !strChar.match(/[^\uFF00-\uFFFF]/g)){
                    all_Num += 2;
                    strCharCounter += 2;
                }else{
                    all_Num ++;
                    strCharCounter ++;
                }
                strContent += strChar
            }
        }
        $('textContent').value = theTextArea.value;
        return strContent;
    },
    validateEmail:function(email_value){
        var pattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/ ;
        var email_list = email_value.split(";");
        for(var i = 0 ; i < email_list.length; i++){
            if(email_list[i].blank())
                continue;
            if(!pattern.test(email_list[i].strip()))
                return false;
        }
        return true;
    }
}

