include(PUSH_P+"js/push_config.js");
var CurrentStep = 1;

var tagslist = new Array();

var imgsrc;      // image urls return from parsing
var imgs;        // image objects

var lang = '0';
var rate = '0';
var mmurl = null;
var expertMode = 0;

var selectedImage = 'NULL';
var selectedImageBkgd = 'yellow';
var lastSelected = 'imagebox_screen';

var selectedMainTag = null;

var backup_url = null;
var from_url = null;

var categoryShown = -1;

var finished = false;

var failures = 0;

function updateSE(id){
   e = $('submit_list_id_'+id);
   d = $('submit_se'+id);
   if(e.checked) d.show();
   else d.hide();
}

function ChangeStep() {
   for (i = 1; i <= 5; ++i) {
      if (!expertMode || CurrentStep == 1) {
         if ( i == CurrentStep ) 
            Element.show('submit_step'+i);
         else 
            Element.hide('submit_step'+i);
      } else {
         // in expert mode && current step = 2~5  
         if ( i != 1 ) 
            Element.show('submit_step'+i); 
         else
            Element.hide('submit_step'+i);
      }
   }
   
   if (!expertMode) window.scrollTo(0,0);
   
   // enable/disable input fields in submit_step1   
   /*if ( CurrentStep == 1) {
      fields = $A($('submit_step1').getElementsByTagName('input'));
      fields.each( function(elem) {
         Field.enable(elem);
      });   
   } else {
      fields = $A($('submit_step1').getElementsByTagName('input'));
      fields.each( function(elem) {
         Field.disable(elem);
      });      
   }*/
}

function backStep() {
   switch (CurrentStep) {
      case 2: CurrentStep = 1; break;
      case 4: CurrentStep = 2; break;
      case 5: CurrentStep = 4; break;
   };
   ChangeStep();
}

function toExpertMode(var_expert) {
   var expert_nodes = $A(document.getElementsByClassName('expert'));
   var wizard_nodes = $A(document.getElementsByClassName('wizard'));
   
   if (var_expert) {
   // from wizard to expert   
      expertMode = 1;            
      wizard_nodes.each( function(elem) {
         Element.hide(elem);
      });
      expert_nodes.each( function(elem) {
         Element.show(elem);
      });
      Element.addClassName('expert_tab','active');
      if( Element.hasClassName('wizard_tab','active') )
         Element.removeClassName('wizard_tab','active');
   } else {
      // from expert to wizard   
      expertMode = 0;      
      expert_nodes.each( function(elem) {
         Element.hide(elem);
      });
      wizard_nodes.each( function(elem) {
         Element.show(elem);
      });
      Element.addClassName('wizard_tab','active');
      if( Element.hasClassName('expert_tab','active') )
         Element.removeClassName('expert_tab','active');
   }   

   ChangeStep();
}


/*-----------------------------------------
   Step 1 function
*/
function ReportError(rsobj) {
   nopost_blog = '感謝您的分享！<br>此部落格主人已在哈部落設定為，只允許部落格主人或是部落格主人與朋友分享此部落格的文章。'
   switch (rsobj.type) {
   case 'not_login' : 
      Element.update('url_problem', "<div class='formErrorMsg'>"+error_not_login+"</div>");
      break;
   case 'no_url' :
      Element.update('url_problem', '<div class="formErrorMsg">'+error_no_url+'</div>');
      break;
   case 'non_ascii' :
      temp = '<div class="formErrorMsg">'+error_chinese_url+'</div>';
      langs = ['utf8', 'big5', 'gb'];
      for (var i=0; i<langs.length; ++i) {
         s = eval('rsobj.urls.'+langs[i]);
         temp += '<div><input type="button" value="'+langs[i]+'" class="langChoice" onClick="setURL(\''+s+'\')">'+
         '<a href="'+s+'" onclick="return preview(\''+s+'\',-1,\''+langs[i]+'\')">'+s+'</a></div>';
      }
      Element.update('url_problem', temp);
      Element.hide('step1_button_div');
      Element.show('step1_button_confirm_div');
      break;
   case 'posted' :
      temp = '<div class="formErrorMsg">'+error_duplicated_post+'</div>';
      Element.update('url_problem', temp+rsobj.posts);
      Element.hide('step1_button_div');
      Element.show('step1_button_confirm_div');
      $('url_text').disabled = true;
      break;
   case 'not_exist' :
      ++failures;
      Element.update('url_problem', "<div class='formErrorMsg'>"+error_dead_link+"</div>");
      break;
   case 'blog_nopost' :
      Element.update('url_problem', "<div class='formErrorMsg'>"+nopost_blog+"</div>");
      break;
   case 'forbidden' :
      Element.update('url_problem', "<div class='formErrorMsg'>"+forbidden_post+"</div>");
      break;
   case 'location' :
      temp = '<div class="formErrorMsg">'+yahoo_news_replaced+
      '<a target="_blank" href="'+rsobj.location+'">'+rsobj.location+'</a></div>';
      Element.update('url_problem', temp);
      $('url_text').value = rsobj.location;
      break;
   case 'block_post':
      Element.update('url_problem', "<div class='formErrorMsg'>"+rsobj.block_reason+"</div>");
      break;
   default :
      Element.update('url_problem', "<div class='formErrorMsg'>"+error_unknown+"</div>");
      break;
   }
}

function checkURL( url_id ){
   $(url_id).value = $F(url_id).strip();
   // no url 
   if ($F(url_id).length == 0) {
      return error_no_url;
   }
   // fix mis-typed http://
   if (m = $F(url_id).match(/^h?ttp:\/\/?([^#]+)/i)) {
      $(url_id).value = 'http://'+m[1];
   }
   // alert not support scheme
   if ((m = $F(url_id).match(/^(.{1,10}):\/\/(.+)/i)) && m[1] != 'http') {
      return error_not_support+m[1];
   }
   // add http://
   if (!$F(url_id).match(/^http:\/\/(.+)/i)) {
      $(url_id).value = 'http://'+$F(url_id);
   }
   // youtube
   if (m = $F(url_id).match(/^http:\/\/([^.]+\.)?youtube.com(\.?)\/watch\?(.*?)v=([^&]+)/i)) {
      $(url_id).value = 'http://www.youtube.com/watch?v='+m[4];
   }
   // udn
   if (m = $F(url_id).match(/^http:\/\/(www.)?udn.com(.*?)([0-9]+).shtml$/i)) {
      $(url_id).value = 'http://forum.udn.com/forum/NewsLetter/NewsPreview?NewsID='+m[3];
   }
   // mobile01
   if (m = $F(url_id).match(/^http:\/\/www\.mobile01\.com\/topicdetail\.php\?f=\d+&t=\d+/i)) {
      $(url_id).value = m[0];
   }
   // zdnet
   if (m = $F(url_id).match(/^http:\/\/www\.zdnet\.com\.tw\/[^\?]+/i)) {
      $(url_id).value = m[0];
   }
   // cnet
   if (m = $F(url_id).match(/^http:\/\/taiwan\.cnet\.com\/[^\?]+/i)) {
      $(url_id).value = m[0];
   }
   // chinatimes
   if (m = $F(url_id).match(/http:\/\/([^.]+\.)?chinatimes\.com.+\.html/i)) {
      $(url_id).value = m[0];
   }
   // wretch trackback
   if (m = $F(url_id).match(/(http:\/\/www\.wretch\.cc\/blog\/)(trackback\.php\?blog_id=)?([^&\/]+)(&article_id=|\/)?(\d+)/i)) {
      $(url_id).value = m[1]+m[3]+'/'+m[5];
   }
   // pixnet
   if (m = $F(url_id).match(/(http:\/\/[^\.]+\.pixnet\.net\/blog\/)(post|trackback\/[^\/]+)(\/\d+).*/i)) {
      $(url_id).value = m[1]+'post'+m[3];
   }
   // nextmedia 
   if (m = $F(url_id).match(/http:\/\/tw\.nextmedia\.com\/([^\/]+)\/article(\/IssueID\/\d+)(\/art_id\/\d+).*/i)) {
      $(url_id).value = 'http://tw.nextmedia.com/'+m[1]+'/article'+m[3]+m[2];
   }
   // yahoo blog
   if (m = $F(url_id).match(/http:\/\/tw\.myblog\.yahoo\.com\/[^\/]+\/article\?mid=\w+/i)) {
      $(url_id).value = m[0];
   }

   return null;
}

function step_func1() {
   
   error = checkURL( 'url_text' );
   if( error ){
      Element.update('url_problem', "<div class='formErrorMsg'>"+error+"</div>");
      return;
   }
   // ok
   // enable all input & textarea fields
   var fields = $A(document.getElementsByTagName('input'));
   fields = fields.concat($A(document.getElementsByTagName('textarea')));
   fields.each( function(elem) {
      Field.enable(elem);
   });  
   
   $('step1_button_next').disabled = true;

   backup_url = $F('url_text');
   Element.update('submit_url_loading', '<img src="'+BASE_P+'images/loading.gif" />');
   showLoading(true);
   new Ajax.Request(PUSH_P+'submit/submitUrl.ajax.php',
      { method: 'get',
        parameters: {'url' : $F('url_text'), 'failures':failures},
        onSuccess: checkUrlCallback });
}

function checkUrlCallback(t) {
   hideLoading();
   rsobj = ej(t.responseText, error_unknown);
   if (!rsobj) {
      $('step1_button_next').disabled = false;
      Element.update('submit_url_loading', '');
      return;
   }
   if (rsobj.res == 'ok') {
      fill(rsobj);
      moveToStep2();
   } else {
      clearStep1();
      ReportError(rsobj);
   }
}

function fill(rsobj) {
   if (rsobj.url) {
      $('url_text').value = rsobj.url;
      backup_url = rsobj.url;
      from_url = rsobj.from_url;
   }
   if ($('url_text')) $('url_value').value = $F('url_text');
   if (rsobj.title && $F('title_text') == '') $('title_text').value = rsobj.title;
   if (rsobj.desc && $F('description_text') == '') $('description_text').value = rsobj.desc;
   updateTitle();
   updateDescription();
   if (rsobj.img) imgsrc = rsobj.img;
   else imgsrc = new Array();
   preloadImages();
   autoLang();
   if (rsobj.rate) { $('adult').checked = rsobj.rate; adult(); }
   if (rsobj.suggestion) {
      temp = '';
      for (var i=0; i<rsobj.suggestion.length; ++i) {
         if ($('check_'+rsobj.suggestion[i])) continue;
         temp += '<span class="nowrap">'+
         '<input type="checkbox" name="special" value="'+rsobj.suggestion[i]+'"'+
         'id="check_'+rsobj.suggestion[i]+'"'+
         'onClick="if (this.checked) addTag(\''+rsobj.suggestion[i]+'\''+
         ', true); else removeTag(\''+rsobj.suggestion[i]+'\');">\n'+
         '<label for="check_'+rsobj.suggestion[i]+'" class="inline">'+rsobj.suggestion[i]+'</label></span>\n';
      }
      if (temp != '') { 
         Element.update('radio_group_tag_suggestion', temp);
         Element.show('suggested_tags');
      }
   }
   if (rsobj.tags) {
      for (var i=0; i<rsobj.tags.length; ++i) {
         addTag(rsobj.tags[i], true);
      }
   }
   if (rsobj.vid) {
      temp = '<div><input type="radio" name="mmurl" onClick="mmurl=null;"/>不顯示影片連結</div>';
      for (var i=0; i<rsobj.vid.length; ++i) {
         if (i==0) mmurl = rsobj.vid[i];
         temp += '<div><input type="radio" name="mmurl" onClick="mmurl=\''+rsobj.vid[i]+'\';"'+
         (i==0?' checked':'')+'>'+
         '<a href="'+rsobj.vid[i]+'" onClick="return showTVBox(\''+rsobj.vid[i]+'\');">'+rsobj.vid[i]+'</a></div>\n';
      }
      if (temp != '') {
         Element.update('vid_preview', temp);
         Element.show('vid_preview_label');
         Element.show('vid_preview');
         Element.show('vid_preview_desc');
      }
   }
}

function clearStep1() {
   Element.update('url_problem', '');
   Element.update('submit_url_loading', '');
   Element.show('step1_button_div');
   Element.hide('step1_button_confirm_div');
   $('step1_button_next').disabled = false;
}

function step_func1_cancel() {
   clearStep1();
   $('url_text').disabled = false;
   $('url_text').value  = '';
   $('title_text').value = '';
   $('description_text').value = '';
   
   updateTitle();
   updateDescription();
   imgsrc = new Array();
   $('url_text').focus();
}

function moveToStep2() {
   clearStep1();
   Element.show('previewData');
   $('inputPopupBtn').setAttribute('href', $F('url_value'));
   CurrentStep = 2;
   ChangeStep();
}

function setURL(url) {
   clearStep1();
   $('url_text').value = url;
}

function autoLang() {
   url = $F('url_text');
   if (url.match(/\.cn/i)) $('lang_jp').checked = true;
   if (url.match(/\.jp/i)) $('lang_jp').checked = true;
}

function addCustomImage() {
   imgurl = $F('image_url_input');
   $('image_url_input').value = '';
   imgsrc.push(imgurl);
   index = imgsrc.indexOf(imgurl);
   img = new Image();
   img.onload = addImage(index, true);
   img.src = imgurl;
   img.isCustom = true; // extra attribute
   imgs.push(img);
}

function preloadImages() {
   selectedImage = 'NULL';
   lastSelected = 'imagebox_screen';
   Element.update('img_preview',
   '<a onclick="selectImage(-1);return false;" id="imagebox_screen"'+
   'style="background:'+selectedImageBkgd+'"'+
   'class="imagebox"><img border="0" id="image_screen" style="margin-top:25px" src="'+BASE_P+'images/defaultT.gif"></a>');
   imgs = new Array(imgsrc.length);
   for (i=0; i<imgsrc.length; ++i) {
      imgs[i] = new Image();
      imgs[i].onload = addImage(i);
      imgs[i].src = imgsrc[i];
   }
}

var currentLargest = 0;
var imgSelectedByUser = false;
function addImage(i, select) {
   return (function() {
   imgs[i].onload = null;
   h = imgs[i].height;
   w = imgs[i].width;
   fw = 143.0;
   fh = 100.0;
   if (h > w) {
      if (h > fh) {
         w = fh / h * w;
         h = fh;
      }
      if (w > fw) {
         h = fw / w * h;
         w = fw;
      }
   } else {
      if (w > fw) {
         h = fw / w * h;
         w = fw;
      }
      if (h > fh) {
         w = fh / h * w;
         h = fh;
      }
   }
   h = parseInt(h);
   w = parseInt(w);
   if (!((h < 25 && w < 25) || h < 15 || w < 15 || (w+h < 50))) {
      new Insertion.Bottom('img_preview',
      '<a onclick="selectImage('+i+');imgSelectedByUser=true;return false;"'+
      'id="imagebox_'+i+'" class="imagebox">'+
      '<img  border="0" id="image_'+i+'" style="margin-top:'+((120-h)/2)+'px;" src="'+imgsrc[i]+'" width="'+w+'" height="'+h+'" />'+
      '</a> ');
      if (select || imgsrc.length == 1 && i == 0) selectImage(i);
      d = imgs[i].height * imgs[i].width;
      if (d > currentLargest) {
         currentLargest = d;
         if (!imgSelectedByUser && d > 14300) selectImage(i);
      }
   }
   });
}

/*-----------------------------------------
   Step 2 function
*/
function check_title_description() {
   $('title_text').value = $F('title_text').strip();
   $('description_text').value = $F('description_text').strip();
   if ($F('title_text').length == 0) {
      alert(error_no_title);
      return false;
   } else if ($F('description_text').length == 0) {
      alert(error_no_description)
      return false;
   } else if ($F('title_text').length > 64) {
      alert(error_title_too_long);
      return false;
   } else if ($F('description_text').length > 256) {
      alert(error_description_too_long);
      return false;
   } else if ($F('title_text') == $F('description_text')) {
      alert(TITLE_AND_CONTAIN_REAPEAT);
      return false;
   }
   $('title_text').value = wideChar2char($F('title_text'));
   updateTitle();
   updateDescription();
   return true;
}

function step_func2() {
   if (!check_title_description()) return false;
   if (!check_mainTag()) return false;
   if (!check_tags()) return false;
   CurrentStep = 4;
   ChangeStep();
   return true;
}

function clearTitle() {
   $('title_text').value = '';
   updateTitle();
   
}

function clearDescription() {
   $('description_text').value = '';
   updateDescription();
}

function updateTitle() {
   if ($('title_a_this')) {
      if ($F('title_text').length == 0)
         Element.update('title_a_this', default_title);
      else
         Element.update('title_a_this', $F('title_text').escapeHTML());
   }
   Element.update('titleLeft', ''+(64-$F('title_text').length));
}

function updateDescription() {
   if ($('description_this')) {
      if ($F('description_text').length == 0)
         Element.update('description_this', default_description);
      else
         Element.update('description_this', $F('description_text').escapeHTML());
   }
   Element.update('descLeft', ''+(256-$F('description_text').length));
}

function selectLang(lg) {lang = lg;}

function adult() {
   if ($('adult').checked) rate = '1';
   else rate = '0';
}

function selectMainTag( id ){
   $('main_tag_'+id).selected = true;
   if( id == '-1' ) return;      
   var cid = $('main_tag_'+id).readAttribute('cid');
   selectedMainTag = $('main_tag_'+id).readAttribute('tag');
   addCategory( cid, selectedMainTag );
   toggleSubCategory( cid );
   $('check_main_'+selectedMainTag).disabled = true;
   if( id == '323' ) // 美食
      Element.show('location_tags');
   else Element.hide('location_tags');
}
function check_mainTag(){
   if( $F('main_tag') == '0' ){
      alert(error_no_main_tag);
      return false;
   }else return true;
}
function mainTag(){
   if( $F('main_tag') == '0' ){
      Element.hide('tag_select_section');
      return;
   }else{
      if( selectedMainTag && selectedMainTag != '-1' ){
         tempMainTag = selectedMainTag;
         selectedMainTag = null;
         $('check_main_'+tempMainTag).disabled = false;
         removeTag(tempMainTag);
      }         
      selectMainTag( $F('main_tag') );
      Element.show('tag_select_section');
   }
}

function addCategory(cid, tag){
   if (categoryShown >= 0 && categoryShown != cid) {
      var elem1='input_sub_category_'+categoryShown
      Element.hide(elem1);
      //Element.removeClassName(elem1, 'active');      
      Element.removeClassName('id_radio_default_category_'+categoryShown, 'active');
   }
   
   var elem2='input_sub_category_'+cid;
   Element.show(elem2);
   //Element.addClassName(elem2, 'active');
   categoryShown = cid;
   
   addTag(tag,true);
   Element.addClassName('id_radio_default_category_'+cid, 'active');   
}

function removeCategory(cid,tag){
   removeTag(tag);
   //Element.removeClassName('id_radio_default_category_'+cid, 'active');   
}

// just show or hide subCategory, but not add any tag
function toggleSubCategory(cid) {
   if (categoryShown>=0) {
      var elem1='input_sub_category_'+categoryShown;   
      Element.hide(elem1);
      //Element.removeClassName(elem1, 'active');      
      Element.removeClassName('id_radio_default_category_'+categoryShown, 'active');      
   }
   
   var elem2='input_sub_category_'+cid;
   Element.show(elem2);
   //Element.addClassName(elem2, 'active');
   Element.addClassName('id_radio_default_category_'+cid, 'active');      
   categoryShown = cid;
}

function addSubCategory(cid, main_tag, sub_tag) {
   addCategory(cid, main_tag);
   addTag(sub_tag, true);
}

function removeSubCategory(cid, main_tag, sub_tag) {
   removeTag(sub_tag, true);
}

   

/*-----------------------------------------
   Step 3 function
*/

function check_tags() {
   if (tagslist.length > 20) {
      alert(error_tags_too_long);
      return false;
   } else if (tagslist.length <= 1) {
      alert(error_tags_too_short);
      return false;
   } else {
      var boxes = $A(document.getElementsByName('default_category'));
      boxes = boxes.select( function (box) {
         return box.checked;   
      }); // return an array of checked boxes
      if (boxes.length > 3) {
         alert(error_category_too_long);
         return false;
      }
   }
   
   return true;
}

function tagAddedBefore(name, remove) {
   for (var i=0; i<tagslist.length; ++i) { // remove from real ds
      if (tagslist[i] == name) {
         if (remove) tagslist.splice(i,1);
         return true;
      }
   }
   return false;
}

function addUserTag() {
   if ($F('tagbox_text').length > 16) {
      alert(error_tag_too_long);
      return false;
   }
   newtag = $F('tagbox_text');
   addTag(newtag, true);
}

function addTag(name, remove) {
   name = wideChar2char(name); // wide char to narrow char
   name = name.replace(/[\$"]/g, '');
   name = name.replace(/^\s+|\s+$/g, '');
   name = name.stripTags();
   if (name == '') return; // nothing entered in text box
   if (tagAddedBefore(name)) return; // same tag
   if (remove && name.charAt(0) != '@') { // removable ?! isSpecial ?
      new Insertion.Bottom('tag_bar', 
         '<a id="tag_'+name+'" '+
         'class="removableTag" onclick="removeTag(\''+
         name.replace(/(['\\])/g, "\\$1")+'\');return false;">'+name+'</a>');
   }
   if ($('tags_this')) {
      if( name.charAt(0) != '@' ){         // not special tag
         new Insertion.Bottom('tags_this', // add to preview box
            '<span id="tag_preview_'+name+'">'+name+'</span> ');
      }
   }
   $('tagbox_text').value = ''; // empty text box
   tagslist.push(name); // push to real ds
   if ($('check_'+name)) $('check_'+name).checked = true; // check again
   if ($('check_main_'+name)) $('check_main_'+name).checked = true;
   if ($('check_sub_'+name)) $('check_sub_'+name).checked = true;      
}

function removeTag(name) {
   if( name == selectedMainTag ){
      alert(error_main_tag_unremovable);
      return false;
   }
   if ($('tag_'+name)) Element.remove('tag_'+name); // remove from tag list
   if ($('tag_preview_'+name)) Element.remove('tag_preview_'+name); // remove from preview box
   tagAddedBefore(name, true); // remove from real ds
   if ($('check_'+name)) $('check_'+name).checked = false; // uncheck again
   if ($('check_main_'+name)) $('check_main_'+name).checked = false;
   if ($('check_sub_'+name)) $('check_sub_'+name).checked = false;   
}

/*-----------------------------------------
   Step 4 function
*/

function step_func4() {
   CurrentStep = 5;
   ChangeStep();
   $('captcha_text').focus();
   return true;
}

function selectImage(x) {
   if (lastSelected) {
      $(lastSelected).style.background = 'white';
   }
   if (x >= 0) {
      $('imagebox_'+x).style.background = selectedImageBkgd;
      selectedImage = $('image_'+x).src;
      lastSelected = 'imagebox_'+x;
   } else {
      $('imagebox_screen').style.background = selectedImageBkgd;
      selectedImage = 'NULL';
      lastSelected = 'imagebox_screen';
   }
   if (!$('imgthumbnail')) return;
   if (x >= 0) {
      $('imgthumbnail').height = $('image_'+x).height;
      $('imgthumbnail').width = $('image_'+x).width;
      $('imgthumbnail').src = $('image_'+x).src;
   } else {
      $('imgthumbnail').height = 69;
      $('imgthumbnail').width = 100;
      $('imgthumbnail').src = '/images/defaultT.gif';
   }
}

/*-----------------------------------------
   final function
*/

function step_func5() {
   if (expertMode) {
      if (!step_func2() || !step_func4())
         return false;
   }
   SubmitPost();
}

function SubmitPost() {

   params = '';
   params += 'url='+encodeURIComponent($F('url_text'));
   params += '&title='+encodeURIComponent($F('title_text'));
   params += '&description='+encodeURIComponent($F('description_text'));
   for (var i=0; i<tagslist.length; ++i) {
      params += '&tags[]='+encodeURIComponent(tagslist[i]);
   }
   params += '&imgurl='+encodeURIComponent(selectedImage);
   params += '&lang='+lang;
   params += '&rate='+rate;
   params += '&main_tag='+$F('main_tag');
   params += '&autotrack='+$('autotrack').checked;
   params += '&text='+encodeURIComponent($F('autosend_status'));
   params += $('update_funp')    && $('update_funp').checked    ? 
             '&update_funp=1'    : '';
   params += $('update_twitter') && $('update_twitter').checked ? 
             '&update_twitter=1' : '';
   params += $('update_buboo')   && $('update_buboo').checked   ? 
             '&update_buboo=1'   : '';
   params += $('update_plurk')   && $('update_plurk').checked   ? 
             '&update_plurk=1'   : '';

   $('done1').disabled = true;
   $('done2').disabled = true;

   if (from_url) params += '&from_url='+encodeURIComponent(from_url);
   if (mmurl) params += '&mmurl='+encodeURIComponent(mmurl);

   params += '&user_code='+encodeURIComponent($F('captcha_text'));
   params += '&op=save';

   Element.update('submit_loading', '<img src="'+BASE_P+'images/loading.gif" />');
   showLoading(true);
   new Ajax.Request(PUSH_P+'post.ajax.php',
      { method: 'post',
        postBody: params,
        onSuccess: SubmitPostCallback });
}

function SubmitPostCallback(t) {
   hideLoading();
   rsobj = ej(t.responseText, error_unknown);
   if (rsobj && rsobj.res == 'ok') {
      if( rsobj.twitter_update ) {
         finished_url = PEOPLE_P+'twitter/?update='+encodeURIComponent(rsobj.twitter_update);
      }
      if( rsobj.buboo_update ) {
         finished_url = PEOPLE_P+'buboo/?update='+encodeURIComponent(rsobj.buboo_update);
      }
      if (!$('submit_mylist_form')) {
         finished = true;
         redirect(finished_url);
         return;
      }
      SubmitToFavo(rsobj.post_id);
   } else {
      Element.update('submit_loading', '');
      $('done1').disabled = false;
      $('done2').disabled = false;
      $('captcha_img').src = PUSH_P+'comment/captcha.php?r='+Math.random();
      $('captcha_text').value = '';
      $('captcha_text').focus();
      if (rsobj.res == 'error' && rsobj.type == 'error_captcha') {
         Element.show('captcha_msg');
      } else if (rsobj.res == 'error' && rsobj.type == 'posted') {
         alert(post_race_condition);
         finished = true;
         redirect('/t'+rsobj.post_id);
      } else {
         alert(error_unknown);
      }
   }
}

function SubmitToFavo(pid) {

   // my favo
   if( document.submit_mylist_form.submit_myfavo.checked ){
      new Ajax.Request( PUSH_P+'doFavoPost.ajax.php',
      {  method: 'get',
         parameters: 'type=add&pid='+pid,
         onSuccess: function(t){
            rsobj = ej( t.responseText );
            if (rsobj.res != 'ok') {
               alert('加入到我的最愛失敗');
            }
            SubmitToList(rsobj.pid);
         }
      });
   }else{
      SubmitToList(pid);
   }
}

function SubmitToList(pid) {

   params = '';
   first = true;
   // append list_id if corresponding checkbox is checked
   if (document.submit_mylist_form.submit_list_id) {
      if (!document.submit_mylist_form.submit_list_id.length) {
         if (document.submit_mylist_form.submit_list_id.checked) {
            first = false;
            params += 'list_id[]='+document.submit_mylist_form.submit_list_id.value;
         }
      } else {
         for (i=0; i<document.submit_mylist_form.submit_list_id.length; ++i) {
            if (document.submit_mylist_form.submit_list_id[i].checked) {
               if (first) {
                  first = false;
                  params += 'list_id[]='+document.submit_mylist_form.submit_list_id[i].value;
               } else {
                  params += '&list_id[]='+document.submit_mylist_form.submit_list_id[i].value;
               }
            }
         }
      }
   }
   if (first == false) { // some list is selected
      params += '&post_id='+pid;
      if ($('submit_mylist_textarea'))
         params += '&desc='+encodeURIComponent($F('submit_mylist_textarea'));
      else
         params += '&desc='+'';

      for(i=0;i<ivlist.length;i++){
         lid = ivlist[i].list_id;
         if($('submit_list_id_'+lid).checked){
            for(j=1;j<=5;j++){
               et = 'extra'+j;
               st = 'score'+j;
               ev= $('submit_'+et+'_'+lid)? encodeURIComponent($F('submit_'+et+'_'+lid)): '';
               sv = $('submit_'+st+'_'+lid)? encodeURIComponent($F('submit_'+st+'_'+lid)): '';
               params += '&se['+lid+']['+et+']='+ev;
               params += '&se['+lid+']['+st+']='+sv;
               params += '&se['+lid+'][pid]='+pid
               params += '&se['+lid+'][list_id]='+lid;
               params += '&se['+lid+'][comment]='+encodeURIComponent($F('submit_mylist_textarea'));
            }
            vr = '';
            for(j=0;j<ivlist[i].listtags.length;++j){
               e = $('submit_lt'+ivlist[i].list_id+'_'+ivlist[i].listtags[j].listtag_id);
               if(e && e.checked){
                  vr += '&se['+lid+'][tag][]='+ivlist[i].listtags[j].listtag_id;
               }
            }
            params += vr;
            params += '&se['+lid+'][member_type]='+$F('submit_member_type_'+lid);
         }
      }

      new Ajax.Request( PICKS_P+'add2list.ajax.php',
         { method: 'post',
           postBody: params,
           onSuccess: function(r){
             finished = true;
             if(isPopup) self.close();
             else redirect(finished_url);
           }
      });
   } else {
      finished = true;
      if (isPopup) self.close();
      else redirect(finished_url);
   }
}

function EditPost(op, post_id) {
   if (!check_title_description()) return;
   if (!check_mainTag()) return false;
   if (!check_tags()) return;
   params = '';
   params += 'post_id='+post_id;
   params += '&title='+encodeURIComponent($('title_text').value);
   params += '&description='+encodeURIComponent($('description_text').value);
   params += '&lang='+lang;
   params += '&rate='+rate;
   params += '&main_tag='+$F('main_tag');
   if (e=$('editImage_div') && Element.visible('editImage_div')) 
      params += '&imgurl='+encodeURIComponent(selectedImage);
   for (var i=0; i<tagslist.length; ++i) {
      params += '&tags[]='+encodeURIComponent(tagslist[i]);
   }
   params += '&op='+op;
   showLoading(true);
   new Ajax.Request(PUSH_P+'post.ajax.php',
      { method: 'post',
        postBody: params,
        onSuccess: function(t) {
            hideLoading();
            rsobj = ej(t.responseText);
            if (rsobj && rsobj.res == 'ok') {
               redirect(finished_url);
            }
        }
   });
}

function confirmDeletePost(msg, post_id) {
   getConfirmBox(msg, 10, 'DeletePost('+post_id+')');
   funpDlg.show('confirmBox');
   $('noBtn').focus();
}

function DeletePost(post_id) {
   params = 'post_id='+post_id+'&op=delete';
   new Ajax.Request(PUSH_P+'post.ajax.php',
      { method: 'post',
        postBody: params,
        onSuccess: function(t) {
            rsobj = ej(t.responseText);
            if (rsobj && rsobj.res == 'ok') {
               redirect(finished_url);
            }
        }
   });
}
function initTagTabSelect(){
   toggleSubCategory(29);
}

function updateURL( pid ){
   getUpdateURLBox(pid);
   funpDlg.show('updateURLBox');
}
function doUpdateURL( pid ){
   // remove error msg and check input url
   Element.update('new_url_msg', '');
   error = checkURL('input_new_url');
   if( error ){
      Element.update('new_url_msg', error);
      return;
   }
   // url ok, do ajax call
   new Ajax.Request(PUSH_P+'edit/updateURL.ajax.php',
      { method: 'post',
        postBody: 'post_id='+pid+'&url='+encodeURIComponent($F('input_new_url')),
        onSuccess: function(t) {
            rsobj = ej(t.responseText);
            if (rsobj && rsobj.res == 'ok') {
               funpDlg.close();
               $('url_value').value = rsobj.url;
               showAlertBox('網址更新成功');
            }else{
               msg = null;
               if( rsobj.type == 'not_login' ){
                  funpDlg.close();
                  showAlertBox('請重新登入');
               }else if( rsobj.type == 'post_not_exist' ){
                  msg = '您欲更新的文章不存在';
               }else if( rsobj.type == 'permission_deny' ){
                  msg = '您不是目前這篇文章的部落格主人';
               }else if( rsobj.type == 'invalid_blog_owner' ){
                  msg = '您更新的網址有誤，或是您不是對應的部落格主人';
               }else if( rsobj.type == 'fail' ){
                  msg = '更新失敗！請確定此網址是否已重複張貼，或重新嘗試';
               }
               if( msg ){
                  Element.update('new_url_msg', msg);
               }
            }
        }
   });
}

function getUpdateURLBox( pid ){
   pd = $('updateURLBox');
   if(pd) return pd;

   msg = staticDesc('您即將更新此篇文章的網址，本功能僅提供給文章所屬部落格的主人。您只能填入同樣是由您認證的部落格網址，且該網址尚未被張貼到推推王。當更新成功後，本篇文章的所屬部落格也會更新為網址對應的部落格。')
       + staticField('網址','<input type="text" id="input_new_url" name="input_new_url" class="fullLength">')
       + staticField(null,'<span id="new_url_msg" class="errorMsg"></span>');

   btns =
   '<input type="button" class="positive" id="trs_submitBtn" value="確認" onclick="doUpdateURL('+pid+')"> '+
   '<input type="button" class="negtive" id="trs_cancelBtn" onclick="funpDlg.close()" value="取消">';

   str = getDialogBox('updateURLBox', 0, msg, btns);
   new Insertion.Bottom(document.body, str);

   return $('updateURLBox');
}

function editImage() {
   Element.hide('editImage_txt');
   Element.show('editImage_div');
   showLoading(true);
   new Ajax.Request(PUSH_P+'submit/editImage.ajax.php', { 
      method: 'get',
      parameters: {'url' : $F('url_value')},
      onSuccess: function(t) {
         hideLoading();
         rsobj = ej(t.responseText, error_unknown);
         if (rsobj) fill(rsobj);
      }
   });
}

function showHideTweetArea() {
   var show = $('update_funp')    && $('update_funp').checked    ||
              $('update_twitter') && $('update_twitter').checked ||
              $('update_buboo')   && $('update_buboo').checked   ||
              $('update_plurk')   && $('update_plurk').checked;
   if (show) Element.show('autosend_window');
   else Element.hide('autosend_window');
   Element.update('autosend_status',$F('title_text'));
}
