//MAIN Listening books JS File
//SOME DYNAMIC FUNCTIONS TO BE USED IN ORDER TO FACILITATE OTHER
//FUNCTIONS IN THIS FILE OR FUNCTIONALITIES ON THE APPLICATION
////////////////////////////////////////////////////////////////

//this function is used by other functions where Ajax calls are being made
//the purpose of the function is to create a animation div on the target element
//while the Ajax call gets completed
function setLoadingicon(target) {
    //set loading icon & message
    DeleteChildNodes(document.getElementById(target));
    var loading = document.createElement('img');
    loading.setAttribute("alt", "...");
    loading.setAttribute("src", "images/ajax-loaderW.gif");
    document.getElementById(target).appendChild(loading);
    document.getElementById(target).innerHTML += '<label> Loading...</label>';
}

//Validation function for different types of inputs
function validateEmail(email){
    var at = email.lastIndexOf("@");

    // Make sure the at (@) sybmol exists and  
    // it is not the first or last character
    if (at < 1 || (at + 1) === email.length)
        return false;

    // Make sure there aren't multiple periods together
    if (/(\.{2,})/.test(email))
        return false;

    // Break up the local and domain portions
    var local = email.substring(0, at);
    var domain = email.substring(at + 1);

    // Check lengths
    if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
        return false;

    // Make sure local and domain don't start with or end with a period
    if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
        return false;

    // Check for quoted-string addresses
    // Since almost anything is allowed in a quoted-string address,
    // we're just going to let them go through
    if (!/^"(.+)"$/.test(local)) {
        // It's a dot-string address...check for valid characters
        if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
            return false;
    }

    // Make sure domain contains only valid characters and at least one period
    if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
        return false;

    return true;
}

//setClass of a DOM element
//for cross browser compatibility
function setClass(element, className) {
    element.setAttribute('className', className);
    element.setAttribute('class', className);
}

//for adding events to elements
//if not used then memory leak is caused by adding already defined events
function AddEvent (Doc,EventType,FunctionName){
    if (typeof Doc.addEventListener != 'undefined') {
        Doc.removeEventListener(EventType, FunctionName ,false);
        Doc.addEventListener(EventType, FunctionName,false );
    }
    else if (typeof Doc.attachEvent != 'undefined') {
        Doc.detachEvent('on' +EventType, FunctionName );
        Doc.attachEvent('on'+EventType, FunctionName );
    }
    else {Doc.onmouseout = FunctionName;} // tradition
}

function getInnerText2(element) {
    var text;
    if (document.all) { text = element.innerText; }
    else { text = element.textContent; }
    return text;
}
function setInnerText(element, text) {
    if (element == null) return;
    if (document.all) { element.innerText = text; }
    else { element.textContent = text }
    return text;
}

//Delete child nodes of any DOM
function DeleteChildNodes(Obj) {
    if (!Obj) { alert('Invalid Object:' + Obj); return; }
    while (Obj.hasChildNodes()) { Obj.removeChild(Obj.firstChild); }
}

//Delete child nodes of any DOM
function DeleteChildNodesByID(ID) {
    DeleteChildNodes(document.getElementById(ID));
}

//delete the object itself
function DeleteMe(el) {
    myObj = document.getElementById(el);
    myObj.parentNode.removeChild(myObj);
}

//delete the parent of Me object
function CloseMe(Me) {
    var parent = Me.parentNode;
    parent.parentNode.removeChild(parent);
    var rlist = document.getElementById('requestList');
    document.getElementById('reqBooksCount').innerHTML = ' ' + rlist.childNodes.length + ' ';
}

function KillMe(Me) {
    var parent = Me.parentNode;
    $("#" + parent).fadeOut("slow");
    parent.removeChild(parent);
}
function CalPad(val) {
    var txt = '' + val;
    if (txt.length === 1) { txt = '0' + txt; }
    return txt;
}

//function sets the watermark on any Editbox
//id=id of the textbox, watermark = text to put as watermark
////////////////////////////////////////////////////////////
function setWatermark(id,watermark,type) {
    if ($("#" + id).val() === "" || type=='reset') { $("#" + id).val(watermark); }
    $("#" + id).focus(function() {
        if (this.value == watermark) { this.value = ""; }
    }).blur(function() {
        if (this.value === "") { this.value = watermark; }
    });
 }
 
 
 var playTabNum, requestTabNum, detailsTabNum, bookmarkTabNum;
 function setTabnumberings(serviceoption) {
     
     if (serviceoption == 1 || serviceoption == 2)
     { playTabNum=0; requestTabNum=1;detailsTabNum = 2;bookmarkTabNum = 3; }

     if (serviceoption == 3)
     { requestTabNum = 0; detailsTabNum = 1; }

     if (serviceoption == 4 || serviceoption == 100)
     { playTabNum = 0; detailsTabNum = 1; bookmarkTabNum = 2; }

 }
 
 //this block is responsible for tooltips on 'A' Links & Images in application
//so when we hover we'll see the available large size image in tooltip
 this.imageTooltip = function() {
     xOffset = 12; yOffset = 12;
     $("a.preview").hover(function(e) {
         this.t = this.title;
         this.title = "";
         var c = (this.t !== "") ? "<br/>" + this.t : "";
         $("body").append("<p id='preview'><img src='" + this.href + "' alt='' />" + c + "</p>");
         $("#preview")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
     },
	function() { this.title = this.t; $("#preview").remove(); });
     $("a.preview").mousemove(function(e) {
         $("#preview")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			;
     });
 };

//we are using this function to keep the selection on screen for the use
//as the user select a rating this function is called to refresh the rating
//control with user selected rating on the screen.
function refreshRating(vote) {
    document.getElementById('rate').value = vote;
    initializeRating(vote);
}
//script for rating control
//======================================
function initializeRating(value){
    $('#divRating').rater({ mediapath: '', value: value, callback: refreshRating });
}
(function($) {
  $.fn.rater = function(options){
    var defaults = {url: 'getrecords.aspx?id=rate', enabled: true, favstar: false,
      favtitle: 'save as favorite', mediapath: '.', value: 0, indicator: true,
      callback: false };
    var holder = $(this);
    var opts = $.extend(defaults, options);
    opts.value = Math.abs(Math.round(opts.value));
    opts.value = opts.value > 5 ? 5 : opts.value;
    var ratingui = ''; 
    var ratingcls = 'star_'+opts.value;
    if(!opts.favstar)
    {
    	ratingui += '<ul class="rating '+ratingcls+'">';
	    for (var i = 1; i <= 5; i++) 
	    {
	    	if(opts.enabled)
	    	 ratingui += '<li class="s_'+i+'"><a href="#" title="'+i+'">'+i+'</a></li>';
	    	else
	    	 ratingui += '<li class="s_'+i+'"><span>'+i+'</span></li>';
	    }
    }
    else
    {
    	ratingui += '<ul class="fav '+ratingcls+'"><li class="s_1">';
    	if(opts.enabled)
    	 ratingui += '<a href="#" title="'+opts.favtitle+'">'+(opts.value==1 ? 0 : 1)+'</a></li>';
      else
        ratingui += '<span>'+(opts.value==1 ? 0 : 1)+'</span></li>';
    }
    if(opts.indicator && !opts.favstar)
      ratingui += '<li class="indicator"><img src="'+opts.mediapath+'indicator.gif" alt="loading" /></li>';
    
    ratingui += '</ul>';

    holder.html(ratingui);
    var indicator = holder.find('ul > li.indicator');
    holder.find('ul > li > a').click(function(){
      var value  = $(this).html();
    	if(opts.callback != false)
    	{
    		opts.callback(value);
    		return false;
    	}
      if(opts.indicator && !opts.favstar)
        indicator.show();
      $.post(opts.url,
        { vote: value },
        function(data){
        	if(opts.indicator && !opts.favstar)
        	 indicator.hide();
			  }
			);
			var newcls = 'star_'+value;
			holder.find('ul').removeClass(ratingcls).addClass(newcls);
      ratingcls = newcls;
      if(!opts.favstar)
      {
      	$(holder.find('ul > li')).each(function(i){
      		if($(this).attr('class') != 'indicator')
	         $(this).html('<span>'+i+'</span>');
	      });
      }
      else { $(this).html(value==1 ? '0' : '1'); }
    return false;
    });
    return this;
} 
})(jQuery);

//collapse the expanded div's dynamically
function CloseExpandedDivs(excDiv){
    //parent div containing all the search results
    var Parent = excDiv.parentNode;
    //go there all the div's in the container and see if any of them is expanded
    //if expanded, then collapse them asap ;)
    for(var i=0; i<Parent.childNodes.length;i++)
    {
        if (Parent.childNodes[i].id!=excDiv.id && Parent.childNodes[i].id.indexOf('@')!=-1){
                if (Parent.childNodes[i].style.display = "block"){
                Parent.childNodes[i].style.display = "none";}
        }
    }
}

//Autocomplete functions
//////////////////////////////////////////// 
function lookup(inputString, event, pageType) {
    if (event.keyCode == 13) { getData(pageType, '', '0', '10', '1'); return; }
//    if (inputString.length == 0) { $('#suggestions').hide(); }
//    else {
//        //we can use loading animation here in textbox while the Ajax
//        //request fetches the results from database
//        $.ajax({
//            type: "POST",
//            url: 'Getrecords.aspx?type=autocomplete&qs=' + inputString,
//            data: '',
//            success: function(response) {
//                $('#suggestions').show();
//                $('#autoSuggestionsList').html(response);
//            }
//        });
//    }
}

//used by onclick event of the autocomplete popup menu
function fill(thisValue) {
//    $('#a').val(thisValue);
//    setTimeout("$('#suggestions').hide();", 200);
}

//refresh custom vertical scroll bar using jScrollPane.js plugin
function drawScrollBar(){
    //$(function() { $('#RightBox').jScrollPane({ showArrows: true });});
    $(function() { $('#divResultsContainer').jScrollPane({ showArrows: true }); });
}

//lreturns a timestamp. Used to avoid IE caching Ajax requestsfunction 
function myTimestamp()
{    tstmp = new Date()
         return tstmp.getTime();
     }
//this function is used to redirect user from Ajax request
//if the session do not exists
     function redirectToLogin() {

         window.location.href('login.aspx?logout=true');
     
      }

