﻿var leftFriendPos = 0;
var topFriendPos = 0;
var storeCustomerid = 0;

// these are labels for the days of the week
var cal_days_labels = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];

// these are human-readable month name labels, in order
var cal_months_labels = ['January', 'February', 'March', 'April',
                     'May', 'June', 'July', 'August', 'September',
                     'October', 'November', 'December'];

// these are the days of the week for each month, in order
var cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

// this is the current date
var cal_current_date = new Date();

function readmore(theblogid) {
    getBlog(theblogid)
    return false;
    //show all of article on its own here
}

function changeCategory(thetypeid) {
    var xmlHttp
    //build product information to be sent to the server
    var params = "blogtype=" + thetypeid + "&rcode=" + getRandomString();
    //server page for dealing with adding a product
    var url = "GetBlogByType.aspx";
    var theBasketStr = ""

    //build a connection
    xmlHttp = newConnection();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    //handle the result
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');
            closeDiv("mainblogpnl")
            showDiv("singleblogpnl", "99999")
            document.getElementById("singleblogpnl").innerHTML = theBasketStr
        }
    }
    //post product data to the server
    xmlHttp.send(params);
    //return false so no page reload takes place
    return false;
}

function searchClick(searchstr, thepage) {

    if (searchstr == "newsearch") {
        searchstr = document.getElementById("searchblog").value;
    }

    if (searchstr.length > 0) {
        var xmlHttp
        //build product information to be sent to the server
        var params = "searchstr=" + searchstr + "&thepage=" + thepage + "&rcode=" + getRandomString();
        //server page for dealing with adding a product
        var url = "SearchBlogs.aspx";
        var theBasketStr = ""

        //build a connection
        xmlHttp = newConnection();
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.setRequestHeader("Content-length", params.length);
        xmlHttp.setRequestHeader("Connection", "close");
        //handle the result
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) {
                theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');
                closeDiv("mainblogpnl")
                showDiv("singleblogpnl", "99999")
                document.getElementById("singleblogpnl").innerHTML = theBasketStr
            }
        }
        //post product data to the server
        xmlHttp.send(params);
        //return false so no page reload takes place

    }
    else {
        alert("You need to enter a search string!")
    }

    return false; 
}

function calendarClick() {
    alert("calendar click here!")
}

function getRandomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
}

function getBlog(blogid)
{
    var xmlHttp
    //build product information to be sent to the server
    var params = "blogid=" + blogid + "&rcode=" + getRandomString();
    //server page for dealing with adding a product
    var url = "GetBlog.aspx";
    var theBasketStr = ""

    //build a connection
    xmlHttp = newConnection();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    //handle the result
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');
            closeDiv("mainblogpnl")
            showDiv("singleblogpnl", "99999")
            document.getElementById("singleblogpnl").innerHTML = theBasketStr
        }
    }
    //post product data to the server
    xmlHttp.send(params);
    //return false so no page reload takes place
    return false;
}


function closeDiv(divName) {
    try {
        document.getElementById(divName).style.display = "none";
        document.getElementById(divName).style.zIndex = "1";
    }
    catch (ex) {

    }
}

// show any div ia a z index and display value, default is 99999
function showDiv(divName, zIndex) {
    if (zIndex.length < 1) {
        zIndex = "99999";
    }
    document.getElementById(divName).style.display = "";
    document.getElementById(divName).style.zIndex = zIndex;
}


function replaceIllegalCharacters(theStr) {
    theStr = theStr.replace(/^\s+|\s+$/g, '', "g");
    theStr = theStr.replace("&nbsp;", ' ', "g");
    theStr = theStr.replace(/\u00a0/g, '');
    theStr = theStr.replace(new RegExp("&nbsp;", "g"), " ");
    theStr = theStr.replace(new RegExp("&", "g"), '%amp');
    //theStr = theStr.replace(new RegExp("\?", "g"), '%que');
    //theStr = theStr.replace("?", "%que", "g");
    theStr = theStr.replace(/\?/g, '%que');
    theStr = theStr.replace(new RegExp("@", "g"), '%at');
    theStr = theStr.replace(/\#/g, 'h%h', "g");
    theStr = theStr.replace(new RegExp("!", "g"), '%exp');
    theStr = theStr.replace(/\$/g, '%dollor');
    theStr = theStr.replace(new RegExp("£", "g"), '%pound');
    theStr = theStr.replace(new RegExp("\'", "g"), '%squ');
    theStr = theStr.replace(new RegExp("\"", "g"), '%dqu');
    theStr = theStr.replace(/\+/g, '%2B');
    //theStr = theStr.replace("+", "%2B", "g");
    theStr = theStr.replace(new RegExp("=", "g"), "%eq");
    //theStr = theStr.replace("=", "%eq", "g");
    theStr = theStr.replace(/\n/g, "<br />");
    //alert("removed js spaces! " + theStr)

    return theStr;

}


function addIllegalCharacters(theStr) {
    theStr = theStr.replace(/^\s+|\s+$/g, '', "g");
    theStr = theStr.replace(new RegExp("%amp", "g"), "&");
    theStr = theStr.replace(new RegExp("%que", "g"), "?");
    theStr = theStr.replace(new RegExp("%at", "g"), "@");
    theStr = theStr.replace(new RegExp("h%h", "g"), '#');
    theStr = theStr.replace(new RegExp("%exp", "g"), "!");
    theStr = theStr.replace(new RegExp("%dollor", "g"), "$");
    theStr = theStr.replace(new RegExp("%pound", "g"), "£");
    theStr = theStr.replace(new RegExp("%squ", "g"), "\'");
    theStr = theStr.replace(new RegExp("&#34;", "g"), "\"");
    theStr = theStr.replace(new RegExp("&#39;", "g"), "\'");
    theStr = theStr.replace(new RegExp("&amp;#34;", "g"), "\"");
    theStr = theStr.replace(new RegExp("&amp;#39;", "g"), "\'");
    theStr = theStr.replace(new RegExp("%dqu", "g"), "\"");
    theStr = theStr.replace(new RegExp("%2B", "g"), "+");

    return theStr;

}

function getAllBlogs(thepage) {

    var xmlHttp
    //build product information to be sent to the server
    var params = "thepage=" + thepage + "&rcode=" + getRandomString();
    //server page for dealing with adding a product
    var url = "GetAllBlogs.aspx";
    var theBasketStr = ""

    //build a connection
    xmlHttp = newConnection();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    //handle the result
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');
            closeDiv("singleblogpnl") //singleblogpnl
            showDiv("mainblogpnl", "99999")
            document.getElementById("mainblogpnl").innerHTML = theBasketStr
        }
    }
    //post product data to the server
    xmlHttp.send(params);
    //return false so no page reload takes place
    return false;

}

function emailFriend(ele, blogid) {
    showDiv("emailfriendpnl", "99999");
    findPos(ele);
    document.getElementById("emailfriendpnl").style.left = leftFriendPos + "px";
    document.getElementById("emailfriendpnl").style.top = topFriendPos + "px";
    //document.getElementById("emailfriendpnl").style.backgroundColor = "#0000ff";
    //hidden form field
    document.getElementById("friendsname").value = "";
    document.getElementById("friendsemail").value = "";
    document.getElementById("yourname").value = "";
    document.getElementById("youremail").value = "";
    document.getElementById("theblogid").value = blogid;
}


function validEmail(emailAddrID, byvalue)	//---------validEmail()------------checks email validity---------------
{
    var errorString = "";
    var error = false;
    var email = ""
    if (byvalue) {
        email = emailAddrID;
    }
    else {
        email = document.getElementById(emailAddrID).value;
    }

    invalidChars = "/:,; ";
    if (email == "")//email not entered
    {
        errorString = "You have not entered any email address.\n";
        error = true;
    }

    for (i = 0; i < invalidChars.length; i++)//checks for the invalid characters
    {
        badChar = invalidChars.charAt(i)
        if (email.indexOf(badChar, 0) > -1) {
            if (badChar == ' ') {

                errorString = errorString + "Error: Email must not contain spaces.\n";
                error = true;
            }
            else
                errorString = errorString + "Error: Email must not contain the character: ' " + badChar + " '.\n";
            error = true;
        }
    }

    atPos = email.indexOf("@", 1); //checks position
    if (atPos == -1) {
        errorString = errorString + "Email Error: Misplaced ' @ ' symbol.\n";
        error = true;
    }
    if (email.indexOf("@", atPos + 1) != -1)//checks pos
    {
        errorString = errorString + "Email Error: Misplaced ' @ ' symbol.\n";
        error = true;
    }
    periodPos = email.indexOf(".", atPos)//checks point for .provider
    if (periodPos == -1) {
        errorString = errorString + "Email Error: Misplaced ' . ' symbol.\n";
        error = true;
    }
    if (periodPos + 3 > email.length)//checks length of provider atleast 3 as standard
    {
        errorString = errorString + "Email Error: Error with right hand side of address.\n";
        error = true;
    }
    if (error) {
        alert(errorString + "Please correct.");
        return false;
    }
    for (i = 0; i < email.length; i++)//checks for 'www' in email address
        if (email.charAt(i) == 'w' && email.charAt(i + 1) == 'w' && email.charAt(i + 2) == 'w' && wwwCheck == true) {
        if (confirm("Caution: WWW is for surfing the web, it is not usually part of an email address.\nClick OK to confirm or cancel to correct address.") == false) {
            return false;
        }
        else
            wwwCheck = false;
    }

    return true;
}


function emailToFriend() {


    var friendsname = replaceIllegalCharacters(document.getElementById("friendsname").value);
    var friendsemail = replaceIllegalCharacters(document.getElementById("friendsemail").value);
    var yourname = replaceIllegalCharacters(document.getElementById("yourname").value);
    var youremail = replaceIllegalCharacters(document.getElementById("youremail").value);
    var blogidpi = document.getElementById("theblogid").value




    if (validEmail("friendsemail", false) && validEmail("youremail", false)) {


        var xmlHttp;
        //build product information to be sent to the server
        var params = "friendsname=" + friendsname + "&blogid=" + blogidpi + "&friendsemail=" + friendsemail + "&yourname=" + yourname + "&youremail=" + youremail + "&rcode=" + getRandomString();
        //server page for dealing with adding a product
        var url = "SendBlogToFriend.aspx";
        var theBasketStr = ""

        //build a connection
        xmlHttp = newConnection();
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.setRequestHeader("Content-length", params.length);
        xmlHttp.setRequestHeader("Connection", "close");
        //handle the result
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) {
                theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');
                document.getElementById("friendsname").value = "";
                document.getElementById("friendsemail").value = "";
                document.getElementById("yourname").value = "";
                document.getElementById("youremail").value = "";
                closeDiv("emailfriendpnl");
                alert("Blog Sent!");
            }
        }
        //post product data to the server
        xmlHttp.send(params);
        //return false so no page reload takes place
    }
    return false;
  
  
    
   
    
    //alert("sending email!");
}

function getY(oElement) {
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function findPos(obj) {
    var curleft = 0;  
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);

    }
    leftFriendPos = curleft;
    topFriendPos = curtop; 
}

function showPostCommentForm(ele, theblogid, customerid) {
    showDiv("commentformpnl", "99999");
    findPos(ele);
    document.getElementById("commentformpnl").style.left = leftFriendPos + "px";
    document.getElementById("commentformpnl").style.top = parseInt(topFriendPos)-100 + "px";
    document.getElementById("commentformpnl").style.border = "3px solid #000000";
    document.getElementById("commentname").value = "";
    document.getElementById("commentemail").value = "";
    document.getElementById("commenttitle").value = "";
    document.getElementById("commentbody").value = "";
    document.getElementById("commentblogid").value = theblogid;
    storeCustomerid = customerid;
    return false;
    //'3px solid red'

}

function postComment() {
    //post to server
    var thename = replaceIllegalCharacters(document.getElementById("commentname").value);
    var thecomment = replaceIllegalCharacters(document.getElementById("commentbody").value);
    var theemail = replaceIllegalCharacters(document.getElementById("commentemail").value);
    var thetitle = replaceIllegalCharacters(document.getElementById("commenttitle").value);
    var blogid = replaceIllegalCharacters(document.getElementById("commentblogid").value);
    
    var xmlHttp;
    //build product information to be sent to the server
    var params = "name=" + thename + "&customerid=" + storeCustomerid + "&comment=" + thecomment + "&email=" + theemail + "&title=" + thetitle + "&blogid=" + blogid + "&rcode=" + getRandomString();
    //server page for dealing with adding a product
    var url = "PostComment.aspx";
    var theBasketStr = ""

    //build a connection
    xmlHttp = newConnection();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    //handle the result
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');

            if (theBasketStr == "true") {
                document.getElementById("commentname").value = "";
                document.getElementById("commentbody").value = "";
                document.getElementById("commentemail").value = "";
                document.getElementById("commenttitle").value = "";
                document.getElementById("commentblogid").value = "";
                closeDiv("commentformpnl");
                getAllBlogs('0')
            }
            else {
                alert("There was an error posting your comment!");
            }
            //alert("Blog Sent!");
        }
    }
    //post product data to the server
    xmlHttp.send(params);
    //return false so no page reload takes place
    return false;
    
    
    
    
}

function showComments(thetr, theblogdiv, thepage) {
    // get comments, show thetr,  add to theblogdiv.
    var xmlHttp
    //build product information to be sent to the server
    var params = "thepage=" + thepage + "&blogid=" + thetr.replace("commentpnl", "").replace("commentpnlind", "").replace("ind", "").replace("type", "").replace("date", "").replace("commentpnldate", "").replace("commentpnltype", "") + "&rcode=" + getRandomString();
    //server page for dealing with adding a product
    var url = "GetComments.aspx";
    var theBasketStr = ""

    //build a connection
    xmlHttp = newConnection();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    //handle the result
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');
            if (theBasketStr.length > 0) {
                //alert("here! " + theBasketStr);
                showDiv(thetr, "99999")
                showDiv(theblogdiv, "99999")
                document.getElementById(thetr).style.display = "";
                document.getElementById(theblogdiv).style.display = "";
                document.getElementById(theblogdiv).innerHTML = theBasketStr;
               //alert("div shown with " + theBasketStr + " tr is " + thetr + " div is " + theblogdiv)
            }
            else {
                alert("There are no comments associated with this blog!")
            }
        }
    }
    //post product data to the server
    xmlHttp.send(params);
    //return false so no page reload takes place
    return false;
}

function closeCommentForm() {
    closeDiv("commentformpnl");
    return false;
}

function closeComments(thecommentdivid, secondarydiv, typediv, datediv) {
    try {
        document.getElementById(thecommentdivid).style.display = "none";
    }
    catch (exc) {

    }

    try {
        document.getElementById(secondarydiv).style.display = "none";
    }
    catch (exc) {

    }
    try {
        document.getElementById(typediv).style.display = "none";
    }
    catch (exc) {

    }
    try {
        document.getElementById(datediv).style.display = "none";
    }
    catch (exc) {
        //alert("error closing " + datediv)
    }
    //alert("set")

    return false;
    
}

function closeFriendWindow() {
    closeDiv("emailfriendpnl");
    return false;
}


function Calendar(month, year) {
    this.month = (isNaN(month) || month == null) ? cal_current_date.getMonth() : month;
    this.year = (isNaN(year) || year == null) ? cal_current_date.getFullYear() : year;
    this.html = '';
}

Calendar.prototype.generateHTML = function() {

    // get first day of month
    var firstDay = new Date(this.year, this.month, 1);
    var startingDay = firstDay.getDay();

    // find number of days in month
    var monthLength = cal_days_in_month[this.month];

    // compensate for leap year
    if (this.month == 1) { // February only!
        if ((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0) {
            monthLength = 29;
        }
    }

    // do the header
    var monthName = cal_months_labels[this.month]
    //class="calendar-table"
    var html = '<table class="contentBodyFont" style="font-size:8pt;">';
    html += '<tr><th colspan="7">';
    html += monthName + "&nbsp;" + this.year;
    html += '</th></tr>';
    //html += '<tr><th colspan=7';
    //class="calendar-header"
    
    html += '<tr>';
    //class="calendar-header-day"
    for (var i = 0; i <= 6; i++) {
        html += '<td>';
        html += cal_days_labels[i];
        html += '</td>';
    }
    html += '</tr><tr>';

    // fill in the days
    var day = 1;
    // this loop is for is weeks (rows)
    for (var i = 0; i < 9; i++) {
        // this loop is for weekdays (cells)
        //class="calendar-day"
        for (var j = 0; j <= 6; j++) {
            html += '<td  style="cursor:pointer;" onclick="calendarDayClick(\'' + day + '/' + (this.month+1) + '/' + this.year + '\')">';
            if (day <= monthLength && (i > 0 || j >= startingDay)) {
                html += day;
                day++;
            }
            html += '</td>';
        }
        // stop making rows if we've run out of days
        if (day > monthLength) {
            break;
        } else {
            html += '</tr><tr>';
        }
    }
    html += '</tr></table>';
    
    var datestr = ""
    datestr += "<br /><a href='#' style='text-decoration:none;' onclick=\"return showCalendar('" + addMonth(cal_current_date, -1) + "')\">Previous</a>&nbsp;<a href='#' style='text-decoration:none;' onclick=\"return showCalendar('" + addMonth(cal_current_date, 1) + "')\">Next</a><br />";
   //alert("datestr is " + datestr);
    html += datestr
    //html += "<br /><span onclick=showCalendar('" + addMonth(new Date(), -1).toLocaleDateString() + "')>Previous</span>&nbsp;<span onclick=showCalendar('" + addMonth(new Date(), 1).toLocaleDateString() + "')>Next</span>";
   // html += "<br /><span onclick=showCalendar('" + addMonth(new Date(), -1).toLocaleString() + "')>Previous</span>&nbsp;<span onclick=showCalendar('" + addMonth(new Date(), 1).toLocaleString() + "')>Next</span>";
    //html += "<br /><span onclick=showCalendar('" + addMonth(new Date(), -1).toUTCString() + "')>Previous</span>&nbsp;<span onclick=showCalendar('" + addMonth(new Date(), 1).toUTCString() + "')>Next</span>";
    //html += "<br /><span onclick=showCalendar('" + addMonth(new Date(), -1) + "')>Previous</span>&nbsp;<span onclick=showCalendar('" + addMonth(new Date(), 1) + "')>Next</span>";

    this.html = html;
}

Calendar.prototype.getHTML = function() {
    return this.html;
}

function showCalendar(datepassedin) {
    cal_current_date = new Date(datepassedin)
    var cal = new Calendar();
    cal.generateHTML();
    document.getElementById("calendarplaceholder").innerHTML = cal.getHTML();
    return false;
}

function addMonth(d,month){
  t  = new Date (d);
  t.setMonth(d.getMonth()+ month);
  if (t.getDate() < d.getDate())
{
      t.setDate(0);
  }
  /*alert("date string is " + t.toDateString())
  alert("toLocaleDateString string is " + t.toLocaleDateString())
  alert("toLocaleString() string is " + t.toLocaleString())
  alert("ttoString() string is " + t.toString())
  alert("toUTCString() string is " + t.toUTCString())*/
  return t;

}

function calendarStartup() {
    //alert("here!")
    if (document.getElementById("calendarplaceholder")) {
        var thedate = new Date();
        cal_current_date = thedate;
        var cal = new Calendar();
        cal.generateHTML();
        document.getElementById("calendarplaceholder").innerHTML = cal.getHTML();
    }
}

function calendarDayClick(thedate) {
    //alert(thedate);
    var xmlHttp
    //build product information to be sent to the server
    var params = "blogdate=" + thedate + "&rcode=" + getRandomString();
    //server page for dealing with adding a product
    var url = "GetBlogByDate.aspx";
    var theBasketStr = ""

    //build a connection
    xmlHttp = newConnection();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    //handle the result
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            theBasketStr = xmlHttp.responseText.replace(/^\s+|\s+$/g, '');
            if (theBasketStr.length > 0) {
                closeDiv("mainblogpnl")
                showDiv("singleblogpnl", "99999")
                document.getElementById("singleblogpnl").innerHTML = theBasketStr;
            }
            else {
                alert("There were no blogs posted on that date!")
            }
        }
    }
    //post product data to the server
    xmlHttp.send(params);
    //return false so no page reload takes place
    return false;
}





