$(document).ready(
      function() {
         //$("div.dayofweek").text(getCurrentDateTime());
         hintTextBox("global_search_input", "Search documents, novels, essays and much more...");
         hintTextBox("global_user_name", "user name");
         $('#global_search_button')
               .hover(
                     function() {
                        $('#global_search_button').attr("src",
                              $('#global_context_root').val() + "/images/search-button-hover.gif");
                     },
                     function() {
                        $('#global_search_button').attr("src",
                              $('#global_context_root').val() + "/images/search-button.gif");
                     });

         $('#global_search_button').bind(
               "click",
               function() {
                  if ($('#global_search_input').val() != "" &&
                      !$("#global_search_input").hasClass("textbox_hint")) {
                     window.location.href = $('#global_context_root').val() + "/search/do/q/"
                           + $.url.encode($('#global_search_input').val());
                  }
               });

         $('#global_search_input').keypress(function(event) {
            if (event.keyCode == '13') {
               $('#global_search_button').trigger("click");
            }
         });

         $('div.loginbutton').bind("click", function() {
            if ($("#global_user_name").val() != "" &&
                !$("#global_user_name").hasClass("textbox_hint") &&
                $("#global_password").val() != "") {
               $("#login_form").submit();
            }
         });

         $('#global_user_name').keypress(function(event) {
            if (event.keyCode == '13') {
               $('div.loginbutton').trigger("click");
            }
         });

         $('#global_password').keypress(function(event) {
            if (event.keyCode == '13') {
               $('div.loginbutton').trigger("click");
            }
         });

         $('div.menu-item').hover(function() {
            $(this).addClass("menu-item-hover");
            $(this).removeClass("menu-item");
         }, function() {
            $(this).addClass("menu-item");
            $(this).removeClass("menu-item-hover");
         });

         $("img[src$='images/arrow-left.gif']").hover(function() {
            this.src = $('#global_context_root').val() + "/images/arrow-left-hover.gif";
         }, function() {
            this.src = $('#global_context_root').val() + "/images/arrow-left.gif";
         });

         $("img[src$='images/login.gif']").hover(function() {
            this.src = $('#global_context_root').val() + "/images/login-hover.gif";
         }, function() {
            this.src = $('#global_context_root').val() + "/images/login.gif";
         });

         $("img[src$='images/arrow-right.gif']").hover(function() {
            this.src = $('#global_context_root').val() + "/images/arrow-right-hover.gif";
         }, function() {
            this.src = $('#global_context_root').val() + "/images/arrow-right.gif";
         });

         $('#global_link_signup').bind("click", function() {
            changeCaptchaImg();
            OpenSignUpDialog();
         });

         $('div.buttoncontainer').hover(function() {
            this.className = "buttoncontainer-hover";
         }, function() {
            this.className = "buttoncontainer";
         });

         $('#btnSignUp').click(function() {
            ajax_signup_submit();
         });

         var currentTab = $("#currentTab").val();
         if (currentTab == "AdminHome") {
            $("#adminHomeTab").addClass("menu-item-current");
         }
         if (currentTab == "UserHome") {
            $("#userhomeTab").addClass("menu-item-current");
         }
         if (currentTab == "Home") {
            $("#homeTab").addClass("menu-item-current");
         }
         if (currentTab == "Browse") {
            $("#browseTab").addClass("menu-item-current");
         }
         if (currentTab == "Loop") {
            $("#loopTab").addClass("menu-item-current");
         }
      });

function OpenSignUpDialog() {
   document.getElementById('dvSignUpDialog').style.visibility = 'visible';
   document.getElementById('dvSignUpDialog').style.display = '';
   document.getElementById('dvSignUpDialog').style.top = Math.round((document.documentElement.clientHeight / 2)
         + document.documentElement.scrollTop) - 250 + 'px';
   document.getElementById('dvSignUpDialog').style.left = '240px';

   document.getElementById('MaskedDiv').style.display = '';
   document.getElementById('MaskedDiv').style.visibility = 'visible';
   document.getElementById('MaskedDiv').style.top = '0px';
   document.getElementById('MaskedDiv').style.left = '0px';
   document.getElementById('MaskedDiv').style.width = document.documentElement.clientWidth + 'px';
   document.getElementById('MaskedDiv').style.height = document.documentElement.clientHeight + 'px';
   document.body.style.overflow = 'hidden';

   $("img.closedialog").hover(function() {
      this.src = $('#global_context_root').val() + "/images/close-hover.gif";
   }, function() {
      this.src = $('#global_context_root').val() + "/images/close.gif";
   });
}

function OpenSignUpSuccessDialog() {
   document.getElementById('dvSignUpSuccessDialog').style.visibility = 'visible';
   document.getElementById('dvSignUpSuccessDialog').style.display = '';
   document.getElementById('dvSignUpSuccessDialog').style.top = Math.round((document.documentElement.clientHeight / 2)
         + document.documentElement.scrollTop) - 300 + 'px';
   document.getElementById('dvSignUpSuccessDialog').style.left = '350px';

   document.getElementById('MaskedDiv').style.display = '';
   document.getElementById('MaskedDiv').style.visibility = 'visible';
   document.getElementById('MaskedDiv').style.top = '0px';
   document.getElementById('MaskedDiv').style.left = '0px';
   document.getElementById('MaskedDiv').style.width = document.documentElement.clientWidth + 'px';
   document.getElementById('MaskedDiv').style.height = document.documentElement.clientHeight + 'px';
   document.body.style.overflow = 'hidden';

   $("img.closedialog").hover(function() {
      this.src = $('#global_context_root').val() + "/images/close-hover.gif";
   }, function() {
      this.src = $('#global_context_root').val() + "/images/close.gif";
   });
}
function CloseSignUpDialog() {
   document.getElementById('MaskedDiv').style.display = 'none';
   document.getElementById('dvSignUpDialog').style.display = 'none';
   document.body.style.overflow = 'auto';
}

function CloseSignUpSuccessDialog() {
   document.getElementById('MaskedDiv').style.display = 'none';
   document.getElementById('dvSignUpSuccessDialog').style.display = 'none';
   document.body.style.overflow = 'auto';
}

function Pager(container_id, url, totalPage, pageIndex, indexSize, itemSpacing) {
   this.initializePaging = function() {
      if (totalPage <= 1) {
         return;
      }
      var from = Math.floor(pageIndex / indexSize) * indexSize;
      var to = from + indexSize > totalPage ? totalPage : from + indexSize;
      var html = "";
      for ( var i = from; i < to; i++) {
         if (i != pageIndex) {
            html += "<td class='pagingItem'><a href='" + url + "/p/" + i + "'><span>" + (i + 1) + "</span></a></td>";
         } else {
            html += "<td class='pagingItemHover'><span>" + (i + 1) + "</span></td>";
         }
      }
      if (html != "") {
         if (pageIndex > 0) {
            html = "<td class='pagingItem'><a href='" + url + "/p/" + (pageIndex - 1) + "'><span>Prev</span></a></td>"
                  + html;
         }
         if (pageIndex < totalPage - 1) {
            html += "<td class='pagingItem'><a href='" + url + "/p/" + (pageIndex + 1) + "'><span>Next</span></a></td>";
         }
         if (pageIndex != 0) {
            html = "<td class='pagingItem'><a href='" + url + "'><span>First</span></a></td>" + html;
         }
         if (pageIndex != totalPage - 1) {
            html += "<td class='pagingItem'><a href='" + url + "/p/" + (totalPage - 1) + "'><span>Last</span></a></td>";
         }
         html = "<table cellpadding='0' cellspacing='0'><tr>" + html + "</tr></table>";
      }
      $("#" + container_id).html(html);

      $('td.pagingItem').hover(function(){
         this.className = "pagingItemHover";
      },function(){
         this.className = "pagingItem";
      });
   };
}

function getRatingControl(voted) {
   var rating = "<form class='formRating'>"
         + "   <input type='radio' name='rate_avg' value='1' title='Not so great' disabled='disabled' CHECK1  />"
         + "   <input type='radio' name='rate_avg' value='2' title='Quite good' disabled='disabled' CHECK2  />"
         + "   <input type='radio' name='rate_avg' value='3' title='Good' disabled='disabled' CHECK3  />"
         + "   <input type='radio' name='rate_avg' value='4' title='Great!' disabled='disabled'  CHECK4  />"
         + "   <input type='radio' name='rate_avg' value='5' title='Excellent!' disabled='disabled'  CHECK5   />"
         + "</form>";

   if (voted == 0) {
      rating = rating.replace("CHECK1", "").replace("CHECK2", "").replace("CHECK3", "").replace("CHECK4", "").replace(
            "CHECK5", "");
   }
   if (voted == 1) {
      rating = rating.replace("CHECK1", "checked='checked'").replace("CHECK2", "").replace("CHECK3", "").replace(
            "CHECK4", "").replace("CHECK5", "");
   }
   if (voted == 2) {
      rating = rating.replace("CHECK1", "").replace("CHECK2", "checked='checked'").replace("CHECK3", "").replace(
            "CHECK4", "").replace("CHECK5", "");
   }
   if (voted == 3) {
      rating = rating.replace("CHECK1", "").replace("CHECK2", "").replace("CHECK3", "checked='checked'").replace(
            "CHECK4", "").replace("CHECK5", "");
   }
   if (voted == 4) {
      rating = rating.replace("CHECK1", "").replace("CHECK2", "").replace("CHECK3", "").replace("CHECK4",
            "checked='checked'").replace("CHECK5", "");
   }
   if (voted >= 5) {
      rating = rating.replace("CHECK1", "").replace("CHECK2", "").replace("CHECK3", "").replace("CHECK4", "").replace(
            "CHECK5", "checked='checked'");
   }
   return rating;
}

function buildDetailPopup(data) {
   if (data.error != null) {
      $("#popup_document_detail div.dialogbody").html("<div class='error'>" + data.error + "</div>");
   } else {
      var html = "";
      html = "<div class='title'>" + data["title"] + "</div>";
      if (data["description"] != 'null') {
         html  += "<div class='description'>" + data["description"] + "</div>";
      }
      html  += "<div class='statistic'>Upload Date: " + data["uploadDate"] + "</div>"
            + "<div class='statistic'>Reads: " + data["readed"] + "</div>"
            + "<div class='statistic'>Downloads: " + data["downloaded"] + "</div>"
            + "<div class='statistic'>Uploaded by: <a href='" + $('#global_context_root').val() + "/people/" + data["ownerId"] + "/profile'>" + data["owner"] + "</a></div>"
            + "<div class='statistic'><table cellpadding='0' cellspacing='0'><tr><td>Votes:&nbsp;</td><td>"
            + getRatingControl(data["vote"])
            + "</td></tr></table></div>";
      html  += "<div class='statistic'>Category: <a href=" + $('#global_context_root').val() + "/browse/category/"
               + data["categoryId"] + ">" + data["category"] + "</a></div>";

      $("#popup_document_detail div.dialogbody").html(html);
      $("form.formRating").stars();
   }
}

function buildDetailUserPopup(data) {
   if (data.error != null) {
      $("#popup_user_detail div.dialoguserbody").html("<div class='error'>" + data.error + "</div>");
   } else {
      var html = "";
      html = "<div class='title'>" + data["userName"] + "</div>";
      html  += "<div class='description'>Name: " + data["fullName"] + "</div>";
      html  += "<div class='description'>Member since: " + data["createdDate"] + "</div>";
      html  += "<div class='statistic'>Documents: " + data["totalDocument"] + "</div>"
            + "<div class='statistic'>Subscribers: " + data["totalSubscriber"] + "</div>"
            + "<div class='statistic'>Subscribers To: " + data["totalSubscriberTo"] + "</div>"
            + "<div class='statistic'>Loops: " + data["totalLoop"] + "</div>";
      if (data["isSubscribed"]) {
         html += "<div class='unsubscribebutton'><a id='subscribe_this_people' href='" + $('#global_context_root').val() + "/people/" + data["id"] + "/unsubscribe'> - Unsubscribe this people</a></div>";
      }
      else {
         html += "<div class='subscribebutton'><a id='subscribe_this_people' href='" + $('#global_context_root').val() + "/people/" + data["id"] + "/subscribe'> + Subscribe this people</a></div>";
      }
      $("#popup_user_detail div.dialoguserbody").html(html);
      $("#subscribe_this_people").click(function(e){
         e.preventDefault();
         if ($("#login_user_name").val() == "" ||
             $("#login_user_name").val() == null) {
            alert("Please login before using this function.");
            return;
         }
         var linkObj = this;
         $.getJSON($(this).attr("href"), function(data){
            if (data.error) {
               alert(data.error);
               return;
            }
            if (data.message) {
               alert(data.message);
               if ($(linkObj).parent().attr("class") == "subscribebutton") {
                  $(linkObj).parent().removeClass("subscribebutton");
                  $(linkObj).parent().addClass("unsubscribebutton");
                  $(linkObj).attr("href", $('#global_context_root').val() + "/people/" + data["id"] + "/unsubscribe");
                  $(linkObj).html(" - Unsubscribe this person");
               }
               else {
                  $(linkObj).parent().removeClass("unsubscribebutton");
                  $(linkObj).parent().addClass("subscribebutton");
                  $(linkObj).attr("href", $('#global_context_root').val() + "/people/" + data["id"] + "/subscribe");
                  $(linkObj).html(" + Subscribe to this person");
               }
            }
         }, "json");
      });
   }
}

function ajax_signup_submit() {
   var formData = $("#signUpForm").serialize();
   var submitUrl = $("#signUpForm").attr("action");
   $.getJSON(submitUrl, formData, function(data) {
      var validResult = true;
      if (data["usernameExisted"] != undefined) {
         $("#usernameExisted").text(data["usernameExisted"]);
         validResult = false;
         changeCaptchaImg();
      }
      if (data["confirmPassError"] != undefined) {
         $("#confirmPassError").text(data["confirmPassError"]);
         validResult = false;
         changeCaptchaImg();
      }
      if (data["username"] != undefined) {
         $("#usernameError").text(data["username"]);
         validResult = false;
      }
      if (data["email"] != undefined) {
         $("#emailError").text(data["email"]);
         validResult = false;
      }
      if (data["password"] != undefined) {
         $("#passwordError").text(data["password"]);
         validResult = false;
      }
      if (data["password"] != undefined) {
         $("#passwordError").text(data["password"]);
         validResult = false;
      }
      if (data["firstName"] != undefined) {
         $("#firstnameError").text(data["firstName"]);
         validResult = false;
      }
      if (data["lastName"] != undefined) {
         $("#lastnameError").text(data["lastName"]);
         validResult = false;
      }
      if (data["captcha"] != undefined) {
         $("#captchaError").text(data["captcha"]);
         $("img#captchaImg").attr("src","/signup/captcha?_="+((new Date()).getTime()));
         validResult = false;
      }
      if (validResult == true) {
         CloseSignUpDialog();
         OpenSignUpSuccessDialog();
      }
   });
}

function changeCaptchaImg() {
   var captchaURL = $("#captchaImg").attr("src") + "?" + Math.random();
   $("#captchaImg").attr("src", captchaURL);
}
function getCurrentDateTime() {
   var currentTime = new Date();
   var arday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
   var armonth = new Array("January ","February ","March ","April ","May ","June ","July ","August ","September ", "October ","November ","December ");
   var ardate = new Array("0th","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st");
   return arday[currentTime.getDay()] + " " + armonth[currentTime.getMonth()] + " " + ardate[currentTime.getDate()] + ", " + currentTime.getFullYear();
}
function hintTextBox(id, hintText) {
   $("#" + id).focus(function(){
      if ($(this).hasClass("textbox_hint")) {
         $(this).removeClass("textbox_hint");
         $(this).val("");
      }
   });
   $("#" + id).blur(function(){
      if (jQuery.trim($(this).val()) == "") {
         $(this).val(hintText);
         $(this).addClass("textbox_hint");
      }
   });
   $("#" + id).val(hintText);
   $("#" + id).addClass("textbox_hint");
}
function ShowVideoObject(pContainer, pFileName, pWidth, pHeight)
{
   var s1 = new SWFObject($('#global_context_root').val() + "/images/player.swf", "ply", pWidth, pHeight, "9", "#000000");
   s1.addParam("allowfullscreen", "true");
   s1.addParam("allowscriptaccess", "always");
   s1.addParam("wmode", "transparent");
   var aFileParam = "file=";
   if (pFileName != "")
   {
       aFileParam += $('#global_context_root').val() + "/images/" + pFileName;
   }
   s1.addParam("flashvars", aFileParam + "&image=" + $('#global_context_root').val() + "/images/PlayerPreview.jpg");
   s1.write(pContainer);
}
