$(document).ready(function(){
    $("body").append("<div id='blogImportMain' style='position:absolute; top:10px; left: 10%; width:80%; height:800px; z-index:12000; background-color:white; padding: 10px;'></div>");
    $("#blogImportMain").append("<div id='blogImportClose' style='text-align:right;'><a href='javascript:void(0);' onclick='$(\"#blogImportMain\").hide();'>Close (X)</a></div>");
    $("#blogImportMain").append("<div id='blogImportTitle' style='text-align:center;padding:10px;'>Blog  Importer</div>");
    $("#blogImportMain").append("<div id='blogImportChooser' style='padding:10px;'>Choose a blog from this site to import into: </div>");
    $("#blogImportMain").append("<div id='blogImportXMLArea' style='padding:10px;'>Paste in the Export HTML:<br/><textarea id='blogImportXML' name='blogImportXML' style='width:95%;height:500px;margin:0 auto;'></textarea><div id='blogImportXMLHolder' style='display:none;'></div></div>");
  $("#blogImportMain").append("<div id='blogImportButtonArea' style='text-align:center;padding:10px;'><input type='button' value='Begin Import' id='blogImportButton' onclick='beginImport();'  /></div>");
  $("#blogImportMain").append("<div id='blogImportProgess' style='text-align:center;padding:10px;'></div>");
    var postdata = "json=%7B%22username%22%3A%22api%22%2C%22password%22%3A%22@p1%22%7D";
    $.post("/api2/login", postdata, function(loginData){
        getPages(loginData);
    });
});

var login;
function getPages(loginData){
    login = $.parseJSON(loginData);
    var partnersPage  = "";
    var postdata = "json=";
    postdata += "&auth=" + encodeURIComponent(login.auth);
    postdata += "&token=" + encodeURIComponent(login.token);    
    $.post("/api2/getAllSections", postdata, function(pagesData){getBlogs(pagesData)});
}

function getBlogs(pagesData){
  var pages = $.parseJSON("[" + pagesData + "]");
  var blogURLs = getBlogURLs(pages);
  //alert(blogURLs);
  var blogChooserHTML =  "<select id='blogChooser'  name='blogChooser'>";
  for(var i = 0;i<blogURLs.split('|').length;i++){
  blogURL = blogURLs.split('|')[i];
  if (blogURL.length > 1)
    blogChooserHTML += "<option  value='" + blogURL.split("^")[1] + "'>" + blogURL.split("^")[0] + "</option>";
  }
  blogChooserHTML  += "</select>";
  $("#blogImportChooser").append(blogChooserHTML);
}

function  getBlogURLs(pages){
    var blogURLs = "|";
    for(var i = 0;i<pages.length;i++){
        var page = pages[i];
        if (page.typeName == "Blog"){
             blogURLs += page.urlRelative + "^" + page.id + "|";
        }
        if (page.children.length>0)
            blogURLs  += getBlogURLs(page.children)
    }
    return blogURLs;
}
var totalEntries  = 0;
var entryCount = 0;
function beginImport(){
  $("#blogImportXMLHolder").append(unescape($("#blogImportXML").val()).replace(/<\!\[CDATA\[/mgi,"").replace(/\]\]>/mgi,"").replace(/\&lt\;/mgi,"<").replace(/\&gt\;/mgi,">"));
  totalEntries  = $("#blogImportXMLHolder blogEntry").size();
  $("#blogImportXMLHolder blogEntry").each(function(){
    // 2/16/2010 8:28:00 PM
    var addedDate = $(this).find("addedDate").text();
    var briefDescription = $(this).find("description").text();
    $(this).find("entry a").each(function (){
      var href = $(this).attr("href");
      if (href.indexOf("/") < 1 && href.indexOf("http") < 1)
        $(this).attr("href", "/" + href);
    });
    $(this).find("entry").find("*").each(function (){
      if ($(this).attr("class") && $(this).attr("class") != "")
        $(this).attr("class", "");
      if ($(this).attr("id") && $(this).attr("id") != "")
        $(this).attr("id", "");
      if ($(this).attr("style") && $(this).attr("style") != "")
        $(this).attr("style", "");
    });
    var fullDescription = $(this).find("entry").html();
    var fullText = $(this).find("entry").text();
    if (briefDescription  == "")
    {
      briefDescription = fullText.substr(0,250) + " ...";
    }    
    var title = $(this).find("title").text().replace(/\./mgi, "");
    var permaLink = $(this).find("permaLink").text();
    var domain = permaLink.substr(0, permaLink.indexOf("/", 7));
    createBlogItem(title, addedDate, briefDescription, fullDescription);
    
  });
}

String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

function createBlogItem(title, addedDate, briefDescription, fullDescription){
  var publishDate = addedDate.split(' ')[0];
  var publishAMPM = addedDate.split(' ')[2];
  var publishHour = addedDate.split(' ')[1];
  publishHour = publishHour.split(':')[0];
  var publishMinute = addedDate.split(' ')[1];
  publishMinute = publishMinute.split(':')[1];
  var postId = $("#blogChooser").val();
  var postURL = $("#blogChooser  option[value='" + postId + "']").text();
  if (!postURL.endsWith("/"))
    postURL += "/";
  var postData = "__VIEWSTATE=";
    postData += "&Title=" + encodeURIComponent(title);
    postData += "&PublishDateYes=false&PublishDate="  + encodeURIComponent(publishDate);
    postData += "&PublishDateAlt=" + publishDate.replace(/\//gi, "-");   
    postData += "&PublishDateHour=" + encodeURIComponent(publishHour);   
    postData += "&PublishDateMinute=" + encodeURIComponent(publishMinute);  
    postData += "&PublishDateAMPM=" + encodeURIComponent(publishAMPM);  
    postData += "&articleSummary=" + encodeURIComponent(briefDescription);   
    postData += "&FullDescription=" + encodeURIComponent(fullDescription);     
    postData += "&auth=" + encodeURIComponent(login.auth);    
    postData += "&token=" + encodeURIComponent(login.token);     
  //console.log(postData);
  $.post(postURL + "EditListItem.aspx?action=Add&sectionId="  + postId  + "&itemId=&update=true", postData, function(responseData){entryFinished(responseData);})
}

function entryFinished(responseData){
  entryCount++;
  $("#blogImportProgess").text(entryCount + " out of " + totalEntries +  " complete.");
}
