﻿//---------------------------------------------------------
//  Initialization manager, bootstrap loader technique, lazy progression technique
//---------------------------------------------------------
var sections;
; $(function() {
    //Manage sections before rendering any element of the page
    //Get all needed information to initialize units, information like sections array and html templates
    if (typeof ContentService != 'undefined')
        ContentService.GetSitePreferences(OnSectionsComplete);
});

//---------------------------------------------------------------
//This is a mechanism to call Init function in timly manner sequence
//this sequence is not depend on a constant time out
//it works step by step loading
//a mean of First in First out .. or .. First function in the list is First call
//and the next function waits untill the previouse one ends
//this way we are asure of isolating every AJAX request from its brother
//---------------------------------------------------------------
var oInitFuncList = new Array();
var oNextInitFunctionID = -1;
function CallNextAfterSuccess(results, context, method) {
    if (typeof context == 'undefined' ||
            context == null ||
            typeof context.success == 'undefined' ||
            context.success == null) {
        //do nothing
    }
    else {
        context.success(results, context, method);
    }
    CallNextInitFunction();
}
function CallNextAfterError(results, context, method) {
    if (typeof context == 'undefined' ||
            context == null ||
            typeof context.error == 'undefined' ||
            context.error == null) {
        //do nothing
    }
    else {
        context.error(results, context, method);
    }
    CallNextInitFunction();
}
function CallNextInitFunction() {
    oNextInitFunctionID++;
    if (oInitFuncList.length <= oNextInitFunctionID) {
        oNextInitFunctionID = -1;
        return;
    }
    //
    var evalCode = oInitFuncList[oNextInitFunctionID];
    eval(evalCode);
}
//---------------------------------------------------------------
// Hack chain functions
//---------------------------------------------------------------
var oPreHackChain = new Array(); //invoked before loading sections
var oPostHackChain = new Array(); //invoked after loading sections
function AddToPreHackChain(func) {//path a string call to function which will be evaluated later
    oPreHackChain[oPreHackChain.length] = func;
}
function AddToPostHackChain(func) {//path a string call to function which will be evaluated later
    oPostHackChain[oPostHackChain.length] = func;
}
function RunPreHackChain() {//This function will invoked before invoking the first InitFunction
    for (id = 0; id < oPreHackChain.length; id++) {
        try { eval(oPreHackChain[id]); }
        catch (err) { alert(err); }
    }
}
function RunPostHackChain() {//This function will invoked after invoking the last InitFunction
    for (id = 0; id < oPostHackChain.length; id++) {
        try { eval(oPostHackChain[id]); }
        catch (err) { alert(err); }
    }
}
//---------------------------------------------------------------
function OnSectionsComplete(result, context, methodname) {
    //Put some elements above "contentMainBody" area, which helps to display dynamic areas
    InsertDynamicContent();
    //Use template concept to display dynamic contents
    //Keep track of default template, other templates will be loaded when needed, like what has done in LoadContent
    oDefaultContentTemplate = result.dynamicContent;
    UseTemplate(oDefaultContentTemplate);
    //keep track of the returned sections and list-template
    oListHTML = result.listTemplate;
    sections = result.sections;
    if (typeof sections.length == 'undefined') {
        alert('أقسام الموقع قيد تحديث البيانات ، حاول الدخول بعد قليل');
        return;
    }
    //Execute prehack chain of functions that a user may want to run first before InitFunctions
    RunPreHackChain();
    //Loop through them all
    var timeInterval = 0;
    //var allFuncs = "";
    var iCounter = 0;
    oNextInitFunctionID = -1;
    oInitFuncList = new Array();
    for (id = 0; id < sections.length; id++) {
        var section = sections[id];
        //call initialization function of each unit in each section
        if (section.initFunction != '') {
            var fnc = section.initFunction + '(' + id + ')';
            var evalCode = 'if(typeof ' + section.initFunction + ' != "undefined")' +
                            ' { setTimeout(function(){' + fnc + ';} , ' + timeInterval + ');}  else {CallNextInitFunction();}';
            oInitFuncList[iCounter++] = evalCode;
            //alert(oInitFuncList[iCounter-1]);
            //eval(evalCode);
            //timeInterval += 125;
        } //end of if condition
    } //end of for loop
    //Excute posthack chain functions that a developer may want to run later after InitFunctions
    oInitFuncList[iCounter++] = 'RunPostHackChain();';
    //
    CallNextInitFunction();
}

//---------------------------------------------------------------
//Template supporting
//---------------------------------------------------------------
var oDefaultContentTemplate = "";
var oDevContentTemplate = ""; //alternative template that can be preloaded for later use with functions like LoadContent, OpenInIFrame
function InsertDynamicContent() {
    //insert dynamic content template just after main body of dydnamic content area
    $('#dynamicBody').wrap('<div id="contentMainBody"></div>').wrap('<div id="contentWindow"></div>');
}
function UseTemplate(contentTemplate) {
    $('#contentPlace').remove();
    $('#contentMainBody').after(contentTemplate);
}
function LoadTemplateFromDev(dev) {
    //create your template inside your html file of the main page of the site
    //Take care: don't make a div named "contentPlace"
    //this function will isert this dev for you
    oDevContentTemplate = '<div  id="contentPlace" style="overflow:hidden;display:none;">' + $('#' + dev).html() + '</dev>';
}
function checkElementID(divID) {
    var temp = $('#' + divID).attr('id');
    if (typeof temp == 'undefined')
        return false;
    return true;
}

//---------------------------------------------------------------
//Initialization functions
//---------------------------------------------------------------
//public class Section
//{
//    public string title;
//    public string divID;
//    public string initFunction;
//    public int leafID;
//    public int contentType;
//    public int unitID;
//}
function InitHorzPrayerTimes(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, isHorz: true, success: OnPrayerTimesDataComplete, error: null };
    if (checkElementID(section.divID))
        ContentService.GetPrayerTimes(CallNextAfterSuccess, CallNextAfterError, context);
    else
        CallNextAfterError(null, null, null);
    //getIslamicFinderTimes(section.divID, true);
}

function InitVertPrayerTimes(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, isHorz: false, success: OnPrayerTimesDataComplete, error: null };
    if (checkElementID(section.divID))
        ContentService.GetPrayerTimes(CallNextAfterSuccess, CallNextAfterError, context);
    else
        CallNextAfterError(null, null, null);
    //getIslamicFinderTimes(section.divID, false);
}

function InitArticles(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: null, error: null };
    CallNextAfterSuccess();
}
function InitArticleSummary(sectionID) {
    //this programming unit is used to display a summary  of random article 
    var section = sections[sectionID];
    var context = { section: section, success: OnArticleSummaryComplete, error: null };
    if (checkElementID(section.divID))
        ContentService.GetArticleSummary(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    else
        CallNextAfterError(null, null, null);
}
function InitGliderNews(sectionID) {
    //To display news div after a div
    var section = sections[sectionID];
    var context = { section: section, success: OnLastGliderNewsComplete, error: null };
    if (checkElementID(section.divID))
        ContentService.GetLastGliderNews(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    else
        CallNextAfterError(null, null, null);
}
function InitVerNews(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: OnLastVerNewsComplete, error: null };
    if (checkElementID(section.divID))
        ContentService.GetLastVerNews(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    else
        CallNextAfterError(null, null, null);
}
function InitFatwa(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: OnRandomFatwaComplete, error: null };
    if (checkElementID(section.divID)) {
        ContentService.RandomFatwa(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    }
    else
        CallNextAfterError(null, null, null);
}
function InitSurvay(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: OnSurvayComplete, error: null };
    //    if (checkElementID(section.divID))
    ContentService.GetLastPoll(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    //    else
    //        CallNextAfterError(null, null, null);
}
function InitSurvayWithCooki(sectionID) {
    var section = sections[sectionID];
    section.isCooki = true;
    var context = { section: section, success: OnSurvayComplete, error: null };
    //    if (checkElementID(section.divID))
    ContentService.GetLastPollWithCooki(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    //    else
    //        CallNextAfterError(null, null, null);
}
function InitMedia(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: OnMediaComplete, error: OnMediaError };
    if (checkElementID(section.divID))
        ContentService.GetMediaMap(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    else
        CallNextAfterError(null, null, null);
}
function InitBooks(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: OnBooksComplete, error: null };
    if (checkElementID(section.divID))
        ContentService.GetBooksList(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    else
        CallNextAfterError(null, null, null);
}
function InitBanners(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: OnBannerComplete, error: OnBannerError };
    //if (checkElementID(section.divID))
    ContentService.GetTodaySectionBanners(section.leafID, CallNextAfterSuccess, CallNextAfterError, context);
    //else
    //    CallNextAfterError(null, null, null);
}
function InitHrzNews(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: null, error: null };
    CallNextAfterSuccess();
}
function InitComments(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: null, error: null };
    CallNextAfterSuccess();
}
function InitGustBook(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: null, error: null };
    CallNextAfterSuccess();
}
function InitAlbum(sectionID) {
    var section = sections[sectionID];
    var context = { section: section, success: null, error: null };
    CallNextAfterSuccess();
}
function InitAlbumBoard(sectionID) {
    var section = sections[sectionID];
    if (!checkElementID(section.divID)) {
        CallNextAfterError(null, null, null);
        return;
    }
    //
    var leafID = section.leafID;
    var divID = section.divID;
    var unitID = section.unitID;
    var context = { leafID: leafID, success: OnBoardComplete, error: null,
        divID: divID,
        unitID: unitID,
        section: section, //for latter use
        album: {},
        albummode: $('#' + divID).attr('albumMode'),
        islistview: $('#' + divID).attr('islistview') == 'true',
        caption: $('#' + divID).attr('caption'),
        ispopup: $('#' + divID).attr('ispopup') == 'true',
        imgW: $('#' + divID).attr('imgW'),
        imgH: $('#' + divID).attr('imgH')
    };
    ContentService.GetFirstAlbumOfSection(leafID, unitID, CallNextAfterSuccess, CallNextAfterError, context);
}

//---------------------------------------------------------
//  Album-board of images mode=list/board
//---------------------------------------------------------
var oAlbumBoard = {};
function OnBoardComplete(retrnAlbum, context, methodname) {
    //Assign returned album to a gloable variable .. oAlbumBoard
    oAlbumBoard = context;
    oAlbumBoard.album = retrnAlbum;
    //fill section division
    ShowBoard();
}

function ShowBoard() {
    //Fill division with first approved image of returned album
    for (var id = 0; id < oAlbumBoard.album.images.length; id++) {
        if (oAlbumBoard.album.images[id].approved) {
            //Use first template, which is deticated to display first approved image on main page
            var buf = oAlbumBoard.album.templates[oAlbumBoard.islistview ? 2 : 0];
            //Replace plce holders by real values
            buf = buf.replace(/-URL-/gi, oAlbumBoard.album.images[id].url);
            buf = buf.replace(/-WIDTH-/gi, oAlbumBoard.imgW);
            buf = buf.replace(/-HEIGHT-/gi, oAlbumBoard.imgH);
            buf = buf.replace(/-ALT-/gi, oAlbumBoard.album.images[id].title);
            buf = buf.replace(/-TITLE-/gi, oAlbumBoard.album.images[id].title);
            buf = buf.replace(/-IMGID-/gi, id);
            buf = buf.replace(/-CAPTION-/gi, oAlbumBoard.caption);
            buf = buf.replace(/-ISPOPUP-/gi, oAlbumBoard.ispopup);
            //display now and break out of the loop
            //alert(buf);
            $('#' + oAlbumBoard.divID).html(buf);
            break;
        }
    }
}

function ShowBoardImage(imgID) {
    var buf = GetBoardImage(imgID);
    //boardDetail
    var myBody = $(buf)
                .find('div:first')
                    .attr({ width: oAlbumBoard.imgW * 3, height: oAlbumBoard.imgH * 1 })
                .end();
    var dialog;
    showDialog(oAlbumBoard.album.images[imgID].title, myBody, oAlbumBoard.imgW * 3 + 50, oAlbumBoard.imgH * 1 + 70, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
    return false;
}
function GetBoardImage(imgID) {
    var buf = oAlbumBoard.album.templates[1];
    //Replace plce holders by real values
    buf = buf.replace(/-URL-/gi, oAlbumBoard.album.images[imgID].url);
    buf = buf.replace(/-WIDTH-/gi, oAlbumBoard.imgW);
    buf = buf.replace(/-HEIGHT-/gi, oAlbumBoard.imgH);
    buf = buf.replace(/-ALT-/gi, oAlbumBoard.album.images[imgID].title);
    buf = buf.replace(/-TITLE-/gi, oAlbumBoard.album.images[imgID].title);
    buf = buf.replace(/-DESCRIPTION-/gi, oAlbumBoard.album.images[imgID].description);
    //
    return buf;
}

function ShowBoardList(caption, isPopup) {
    //This function displays album images in a list weither ion dialog or main page
    //image details is viewed by clicking image title in the list
    //oAlbumBoard.ispopup decides which way will be used dialog or main page.
    var param1 = null;
    var param2 = null;
    ShowList(param1, param2, caption, isPopup, OnBoardListAdd, OnBoardListChange);
}
function OnBoardListChange(listDiv, node, context) {
    //Display selected item from the list of articles
    $(listDiv).disable();
    //var buf = GetBoardImage(parseInt(listDiv.value));
    var itemID = $(listDiv).attr('ID');
    itemID = itemID.replace('itemID\_', '');
    var buf = GetBoardImage(parseInt(itemID));
    //
    $('#dataPlace').html(buf);
    $(listDiv).enable(); //enable <select> after filling dataPlace
}
function OnBoardListAdd(listDiv,selectElement, node, context) {
    var itemTemplate = $(selectElement).html();
    //Insrert all items in the list .. as ... options elements
    var selID = -1;
    for (var id = 0; id < oAlbumBoard.album.images.length; id++) {
        //var optionElement = $('<option></option>').attr({ value: id }).html(oAlbumBoard.album.images[id].title);
        var item = $(itemTemplate.replace('display:none', '')
                 .replace(/XQXQX/gi, id)
                 .replace(/QXQXQ/gi, oAlbumBoard.album.images[id].title)
                ).click(function() { OnBoardListChange(this, node, context); });

        $(listDiv).append(optionElement);

        if (oAlbumBoard.album.images[id].approved) {
            selID = id;
        }
    }
    //if (selID > -1)
    //    $(listDiv).val(selID).change();
    //Empty row at the end of the list for proper scrolling
    var item = itemTemplate.replace('display:none', '').replace(/XQXQX/gi, 'A').replace(/QXQXQ/gi, '&nbsp;');
    $(listDiv).append(item);
    //Scroll smothlly to reach target item
    if (selID > -1) {
        var itemID = '#itemID_' + selID;
        $(listDiv).scrollTo(itemID, 3000, { offset: 0 });
        $(itemID, listDiv).focus().click();
    }
        
}

//---------------------------------------------------------
//  Some Animations
//---------------------------------------------------------
; $.fn.puff = function() {
    var position = $(this).position();
    $(this).css({ position: 'absolute', top: position.top, left: position.left })
    .animate(
    {
        opacity: 'hide',
        width: $(this).width() * 5,
        height: $(this).height() * 5,
        top: position.top - ($(this).height() * 5 / 2),
        left: position.left - ($(this).width() * 5 / 2)
    }, 'normal');
    return $(this);
};

; $.fn.drop = function() {
    $(this).css('position', 'relative').animate(
    {
        opacity: '0',
        top: $(window).height() - $(this).height() - $(this).position().top
    },
    'slow',
    function() { $(this).hide(); });
    return $(this);
};

; $.fn.scale = function(w, h) {
    w = (typeof w == 'undefined') ? $(this).width() : w;
    h = (typeof h == 'undefined') ? $(this).height() : h;
    $(this).animate(
    {
        width: w * 2,
        height: h * 2
    }, 'slow');
    return $(this);
};

; $.fn.disable = function() {
    return this.each(function() {
        if (typeof this.disabled != 'undefined') this.disabled = true;
    });
};

; $.fn.enable = function() {
    return this.each(function() {
        if (typeof this.disabled != 'undefined') this.disabled = false;
    });
}
//---------------------------------------------------------
//  Banner Content
//---------------------------------------------------------
; $(LoadPageBannersArray());

function LoadPageBannersArray() {
    //progresive diclosure pattern .. get array of ids of Banners when read
    $.fn.media.mapFormat('gif', 'quicktime');
    var banners = $.makeArray($('div[id^=banner]'));
    banners = $.map(banners, function(elmnt, id) { return $(elmnt).attr('id'); });
    //use custom attribute instead of none displayed div ... parseInt($('div[id^=LeafID_banners]').text());
    var leafID = parseInt($('div[id^=banner]').attr('LeafID'));
    if (leafID)
        ContentService.GetSiteBanners(leafID, banners.join(','), OnBannerComplete, OnBannerError);
}

var oBanners = {};

function OnBannerError(result) {
    //alert("We have no banners!!!");
}

function OnBannerComplete(ZonesList, context, methodname) {
    //Zone: Is a <div> element that is specified to display a group of banners in sequence one after another with specific duration for each
    //ZonesList: Is an array of ZoneNode
    //ZoneNode: Is a class like, {string zoneName; string[] .BannersUrls; string[] .BannersHrefs; int[] .BannersDurations;}
    //zoneName: is the ID of <div ID="zoneName"> element
    //Now loop through ZonesList to take each zoneNode
    $.each(ZonesList, function(id, zoneNode) {
        //no banners!
        //alert(zoneNode.BannersUrls.length);
        if (zoneNode.BannersUrls.length <= 0) return;
        //Now, we are going to add two properties to each single zone "zoneNode"
        //First: a counter to know what is the next banner to display
        zoneNode.counter = -1;
        zoneNode.lastTimeHandle = null;
        //Second: a function to display banners list of that zone using an innovative recursive manner
        //Recursion will be performed depending on setTimeOut function and durations of each banner
        //------------------------------------------------------------------------------------
        //------------------- Start the declaration of zone displaying function --------------
        //------------------- All formal parrameters must be provided when it is called ------
        zoneNode.display = function(zone, DisplayInsuranceOnly) {
            //Tack care of any unplaned mistake like empty banners-lists
            if (zone.BannersUrls.length <= 0)
                return;
            //OR, even undefined formal parameters
            if (typeof DisplayInsuranceOnly == 'undefined')
                DisplayInsuranceOnly = false;
            //step0: Stop last displaying cycle
            if (zoneNode.lastTimeHandle != null) {
                clearTimeout(zoneNode.lastTimeHandle);
                zoneNode.lastTimeHandle = null;
            }
            //step1: Increment counter to know which banner is next
            if (!DisplayInsuranceOnly) {
                ++zone.counter;
                //Re-initialize counter again to keep banners displayed forever in front of visitors 
                if (zone.counter >= zone.BannersUrls.length)
                    zone.counter = 0;
            }
            //step2: Stop last running banner within current zone, "the banner is a media content like audio, vedio, flash or image"
            $('#' + zone.zoneName)
            .each(function() { stopAudio($(this)); })
            //step3: Construct media-like banner inside current zone
            .html(makeMediaAnchor(zone.BannersUrls[zone.counter], '', $('#' + zone.zoneName).width(), $('#' + zone.zoneName).height()))
            .find('a.mymedia')
                .media({
                    autoplay: true,
                    width: $('#' + zone.zoneName).width(),
                    height: $('#' + zone.zoneName).height(),
                    bgColor: 'transparent'
                })
            .end()
            //step4: Display, by makeing this media-like banner visible and wire it with an event of click in case if it has HREF
            .find('div.mymedia')
                .show()
                .click(function() { if (zone.BannersHrefs[zone.counter] != '') window.open(zone.BannersHrefs[zone.counter]); })
			.end()
            //step5: treat click event of images with special run HREF as normal link or JAVASCRIP statment
            .find('img.mymedia')
                .show()
                .click(function() { OnBannerClick(zone.BannersHrefs[zone.counter]); })
                .css({ cursor: 'pointer' })
            .end();
            //step6: Hang up next dispaying cycle after some specific seconds, and take care of negative durations.
            if (zone.BannersDurations[zone.counter] <= 0)
                zone.BannersDurations[zone.counter] = 5;
            zone.lastTimeHandle = setTimeout(function() { zone.display(zone) }, zone.BannersDurations[zone.counter] * 1000);
            //step7: Save zone object for later use
            eval('oBanners.' + zone.zoneName + '=zone;');
            //            //step8: Re-initialize conter again to keep bnners displayed forever in front of our site visitors
            //            if (zone.counter >= (zone.BannersUrls.length - 1))
            //                zone.counter = -1;
        };
        //------------------- End the declaration of zone displaying function --------------
        //----------------------------------------------------------------------------------
        //Executae a single banners-recursive-thread for each single zone, what can be called a self refrencing technique
        zoneNode.display(zoneNode);
    });
}

function DisplayBanners() {
    for (var zone in oBanners) {
        if (typeof oBanners[zone] == 'undefined')
            continue;
        oBanners[zone].display(oBanners[zone], true);
    }
}

function OnBannerClick(sHref) {
    if (sHref.indexOf('javascript:') == 0) {
        eval(sHref.substring(sHref.indexOf(':') + 1, sHref.length));
        return;
    }
    if (sHref != '') {
        window.open(sHref);
        return;
    }
}
//---------------------------------------------------------
//  Survay Content
//---------------------------------------------------------
function OnSurvayComplete(results, context, method) {
    context.section.survayHtml = results;
    context.section.bIsAnswered = false;
    //
    if (checkElementID(context.section.divID)) {
        var survayContext = $('#' + context.section.divID).html(results);
        if (context.section.isCooki)
            StartSurvayWithCooki(survayContext, context.section);
        else
            StartSurvay(survayContext, context.section);
    }
}

; $.fn.CloseDialog = function() { $('.ui-dialog-titlebar-close', $(this).parent()).click().attr('class'); };
function StartSurvay(survayContext, section) {
    var survayQuestionID = $("#survayQuestionID", survayContext).attr("value");
    var survaySelection = -1;
    $("input.survayRadio", survayContext).click(function() { survaySelection = this.value; });
    //remove vote button if voting before
    if (section.bIsAnswered)
        $("img.survayVote", survayContext).remove();
    //wire a click event if existed
    $("img.survayVote", survayContext)
    .click(function() {
        if (survaySelection == -1) {
            alert("برجاء اختيار أحد الأجوبة أولا");
            return;
        }

        var dialog;
        var myBody =
            $('<div id="survayDlg"></div>')
            .html($("div#survayDialogs div:first-child", survayContext).html())
            .find('input:button:first')
                .click(function() {
                    var email = $('.survayEmailTextBox', myBody)[0].value;
                    if ((email == null) || (email == "")) {
                        alert("برجاء إدخال عنوان بريدك الإلكتروني");
                        return;
                    }
                    if (!emailCheck(email)) {
                        alert("برجاء أدخال عنوان صحيح");
                        return;
                    }
                    SurvayVotting(email, survayQuestionID, survaySelection, survayContext);
                    section.bIsAnswered = true;
                    $("img.survayVote", survayContext).hide();
                    if (dialog) {
                        $(dialog).CloseDialog();
                    }
                })
            .end();
        showDialog("أدخل عنوان بريدك الإلكتروني", myBody, 300, 100, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
    });
    //
    $("img.survayResult", survayContext).click(function() {
        SurvayResult(survayQuestionID, survayContext);
    });
}

function StartSurvayWithCooki(survayContext, section) {
    var survayQuestionID = $("#survayQuestionID", survayContext).attr("value");
    var survaySelection = -1;
    $("input.survayRadio", survayContext).click(function() { survaySelection = this.value; });
    //remove vote button if voting before
    if (section.bIsAnswered)
        $("img.survayVote", survayContext).remove();
    //wire a click event if existed
    $("img.survayVote", survayContext)
    .click(function() {
        if (survaySelection == -1) {
            alert("برجاء اختيار أحد الأجوبة أولا");
            return;
        }
        //
        SurvayVotting('use cookie', survayQuestionID, survaySelection, survayContext);
        section.bIsAnswered = true;
        $("img.survayVote", survayContext).hide();
    });
    //
    $("img.survayResult", survayContext).click(function() {
        SurvayResult(survayQuestionID, survayContext);
    });
}

function SurvayVotting(email, questionID, answerID, survayContext) {
    ContentService.Vote(email, questionID, answerID, OnCompleteSurvayVotting, OnContentError, survayContext);
}
function SurvayResult(questionID, survayContext) {
    ContentService.VoteResult(questionID, OnCompleteSurvayVotting, OnContentError, survayContext);
}
function OnCompleteSurvayVotting(results, survayContext, methodname) {
    var myBody =
            $('<div id="survayReport"></div>')
            .html($("div#survayDialogs div:nth-child(2)", survayContext).html())
            .find('table:first-child tbody')
                .append("<tr><td colspan='4' align='center'>" + $("#survayQuestion", survayContext).html() + "</td></tr>")
                .each(function() {
                    var current = this;
                    $.each(results, function(id, obj) {
                        $('<tr></tr>')
                        .append("<td>" + obj.title + "</td>")
                        .append("<td width='50px'>" + obj.voteCount + "</td>")
                        .append("<td width='100px'><div style=\"background-color:red;height:5px; width:" + obj.votePercent * 100 + "px; float:right;\" /></td>")
                        .append("<td width='50px'>" + Math.round(obj.votePercent * 100) + "%</td>")
                        .appendTo(current);
                    })
                })
            .end();
    var dialog;
    showDialog('نتيجة التصويت', myBody, 600, (results.length * 40) + 75, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
}

function DisplaySurvays() {
    var timeInterval = 0;
    for (id = 0; id < sections.length; id++) {
        var section = sections[id];
        //call initialization function of each unit in each section
        if (typeof section.survayHtml != 'undefined') {
            var survayContext = $('#' + section.divID).html(section.survayHtml);
            StartSurvay(survayContext, section);
        }
    }
}
//---------------------------------------------------------
//  Simple gallary of images album
//---------------------------------------------------------
function showGallary(albumID, leafID) {
    //--------------------------------------------------------------------------------
    //leafID is not required, becuase we need only one album not a list of related album
    //I supported leafID here for future use only
    //ContentService.GetAlbums(leafID, OnShowGallary, OnContentError);
    //--------------------------------------------------------------------------------
    //Get only one album from the server, don't return list of albums
    ContentService.GetAlbumByID(albumID, OnShowGallary, OnContentError);
    return false;
}

function OnShowGallary(retrnAlbum, context, methodname) {
    var myBody = $('<div id="simplegallery"></div>');
    var dialog;
    showDialog('ألبوم الصور', myBody, 650, 480, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
    //Convert real Image-URLs-array into JSON array
    //["path_to_image", "optional_link", "optional_linktarget"]. 
    var strArray = '[ ', delim = '';
    for (var id = 0; id < retrnAlbum.images.length; id++) {
        strArray += delim;
        strArray += '["' + retrnAlbum.images[id].url + '","",""]'; //or .. thumbnailurl
        delim = ',\r\n';
    }
    strArray += ' ]';
    strArray = strArray.replace(/\\/g, '/');
    var imageArray = eval(strArray);
    simpleGallery_imagesPath = "images/SimpleGallery";
    //Initiate gallary
    var mygallery = new simpleGallery({
        wrapperid: "simplegallery", //ID of main gallery container,
        dimensions: [600, 400], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
        imagearray: imageArray,
        autoplay: true,
        persist: false,
        pause: 3000, //pause between slides (milliseconds)

        fadeduration: 1000, //transition duration (milliseconds)
        oninit: function() { //event that fires when gallery has initialized/ ready to run
        },

        onslide: function(curslide, i) { //event that fires after each slide is shown
            //curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
            //i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
        }
    });
}

//---------------------------------------------------------
//  News Content
//---------------------------------------------------------

//---------- glider news ---------------------------------
var oGliderArray; //an array of glides/news, a glid is an object of <div> element contains news
var oGliderContainer; //a container to contain auto-scrolling technique
var iCurrentGlider = 0; //currently displayed id glide
var bAllowGliding = true; //stop/move gliding according to mouse motion
var iGliderInterval = 5000; //duration waiting to start scrolling next glide

//event of succefuly retriving data from the server 
function OnLastGliderNewsComplete(results, context, methodname) {
    oGliderArray = $.makeArray($('div.gliderContent', $(results)));
    oGliderContainer = $('div.gliderNewsContainer', $(results));
    iCurrentGlider = 0;
    //wire some functions to mouse over/out events to stop moving and provide user a chance to read current glid
    //bAllowGliding flag will be used to tell PlayGlider about that
    $('#' + context.section.divID)
    .mouseover(function() { bAllowGliding = false; })
    .mouseout(function() { bAllowGliding = true; })
    .css({ height: '84%' });
    //Add togller
    AddTogller(context.section);
    //Now go directly to play gliders
    PlayGlider(iCurrentGlider, context.section, false);
}

function PlayGlider(iGliderID, section, isUp) {
    //This function displays news one by one, (div.gliderContent by div.gliderContent)
    if (bAllowGliding) {
        //Check the correctness of div.gliderContent counter
        if (iGliderID >= oGliderArray.length)
            iGliderID = 0;
        iCurrentGlider = iGliderID;
        var glid = oGliderArray[iCurrentGlider];
        //put content, get its height, animate it top/down
        var mrqu = $('#' + section.divID).html(oGliderContainer);
        mrqu = $('.gliderNewsInner', mrqu).html(glid);
        var height = $(mrqu).height();
        $('div.gliderContent', mrqu).css({ top: (isUp ? height : -height) });
        //start animation
        $('div.gliderContent', mrqu)
        .animate
        (
            { top: 0 },
            1000,
            'linear',
            function() { $(this).css({ top: '0' }); }
        );
    }
    //recursivly call me again after a while to display next news/glid in oGliderArray
    section.lastTimeOut = setTimeout(function() { PlayGlider((bAllowGliding ? ++iCurrentGlider : iCurrentGlider), section); }, iGliderInterval);
}

function AddTogller(section) {
    //This function adds glider togller bellow a given section 
    //1- Create toggler <div> below the given <div id=section.divID>
    $('#' + section.divID).after('<table class="GliderNewsTogller_class"> <tr id="GliderNewsTogller"></tr></table>');
    //2- retrive each glid
    for (id = 0; id < oGliderArray.length; id++) {
        //3- Construct an anchor for each glid, and associate it with a function to display its corresponding glid/news
        var anchor = $('<td><a href="">' + (id + 1) + '</a></td>')
        .click(
        //4- wire anchor event
        //the following function is a click event for <a> element
        //it stops/kills/clears last setTimeOut
        //and then call PlayGrid for particular/corresponding glid in oGliderArray
        //this way, it makes iGliderID to start counting from this particular glid
        function() {
            if (section.lastTimeOut != 'NaN' && section.lastTimeOut != -1) {
                clearTimeout(section.lastTimeOut);
                section.lastTimeOut = -1;
            }
            var iGliderID = parseInt($(this).text()) - 1;
            PlayGlider(iGliderID, section, true);
            return false;
        }
            );
        //5- Add the currently created anchor to the Toggler    
        $('#GliderNewsTogller').append(anchor);
    }
    //
    var archiveAnchor = $('<td><a href="">' + ' .. أرشيف الأخبار' + '</a></td>').click(function() { GetArticlesList(section.leafID, 'أرشيف الأخبار', -1, 2, false); return false; });
    $('#GliderNewsTogller').append(archiveAnchor);
    //<a href="#">&lt;&lt; </a><a href="#">1</a><a href="#">&gt;&gt;</a>
    //border:dashed 1px blue;
}
//---------- vertical news ---------------------------------

function OnLastVerNewsComplete(results, context, methodname) {
    $('#' + context.section.divID).html(results);
    PlayMarque(true, false); //enable=true, stopAtRecent:false
}
function PlayMarque(enable, stopAtRecent) {
    //Playing marque once DOM-tree is being ready
    if (typeof stopAtRecent == 'undefined')
        stopAtRecent = true;
    //
    var marqueName = 'vmarquee';
    if (!checkElementID(marqueName))
        return;
    //    
    var marque = '#' + marqueName;
    //Kill timeout if any
    var timeoutID = parseInt($('#' + marqueName + '_timeout').text());
    if (timeoutID != 'NaN') {
        clearTimeout(timeoutID);
        $('#' + marqueName + '_timeout').empty();
    }
    //Stop marque 
    $(marque).stop();
    //Exit if nothing or stop
    if (!enable || $(marque).height() < $("#marqueecontainer").height())
        return;
    if (!(id = $('#' + marqueName + '_temp').attr('id'))) {
        //A field to save original content height
        $('<div id="' + marqueName + '_height" style="display:none"></div>').text($(marque).height()).appendTo(marque);
        //Duplicate the content of vmarque within itself, to avoid the trailling white space
        $('<div id="' + marqueName + '_temp' + '"></div>').append($(marque).clone()).appendTo(marque);
        //A field to save timeoutID at the end of each animation, 
        //that is, to make it available to kill the timeout in case of interfaring with mousehouver
        $('<div id="' + marqueName + '_timeout" style="display:none"></div>').appendTo(marque);
    }
    //Calculate the apropriate time for the remaining height
    var height = parseInt($('#' + marqueName + '_height').text());
    var duration = ($(marque).position().top + height) * 25;
    //Start animation
    $(marque).animate(
    { top: -height },
    duration,
    stopAtRecent ? 'swing' : 'linear',
    function() {
        $(this).css({ top: '0' });
        //USE SETTIMEOUT .. TO AVOID CALLING STOP() FROM WITHIN CALLBACK
        if (stopAtRecent) {
            var timeoutID = setTimeout('PlayMarque(true,' + stopAtRecent + ');', 1000);
            $('#' + marqueName + '_timeout').text(timeoutID);
        }
        else {
            var timeoutID = setTimeout('PlayMarque(true,' + stopAtRecent + ');', 0);
            $('#' + marqueName + '_timeout').text(timeoutID);
        }
    });
}
//---------------------------------------------------------
//  Articles Content
//---------------------------------------------------------
function OnArticleSummaryComplete(results, context, method) {
    $('#' + context.section.divID).html(results);
}

function GetArticlesList(leafID, mytitle, ID, type, isPopUp) {
    var context = { title: mytitle, ID: (ID ? ID : -1), isPop: ((typeof isPopUp == "undefined") ? true : isPopUp) };
    if (!type)
        type = 1;
    ContentService.ArticlesList(leafID, type, OnArticlelistComplete, OnArticlelistError, context);
    return false;
}

function OnArticlelistError(result) {
    ContentService.RenewArticlesList(function() { alert('من فضلك أعد المحاولة.'); });
}

function OnArticlelistComplete(node, context, methodname) {
    //oListHTML = node.html; //replace by listTemplate in SitePrefrences class of Initialization manager
    ShowList(node, context, context.title, context.isPop, OnArticleListAdd, OnArticleListChange);
}

function OnArticleListChange(listDiv, node, context) {
    $(listDiv).disable();
    var itemID = $(listDiv).attr('ID');
    itemID = itemID.replace('itemID\_', '');
    //alert('itemID:  ' + itemID);
    ContentService.Articl(parseInt(itemID), context.title, function(article) {
        $('#dataPlace').html(article.content);
        $(listDiv).enable();
    },  
                function(error) {
                    $('#dataPlace').html(error);
                    $(listDiv).enable();
                });
}

function OnArticleListAdd(listDiv,selectElement, node, context) {
    var itemTemplate = $(selectElement).html();
    //Insrert all items in the list in the ofrm of DIV elements
    $.each(node.nodes, function(id, obj) {
        //obj.url: It is the article ID
        var item = $(itemTemplate.replace('display:none', '')
                 .replace(/XQXQX/gi, $.trim(obj.url).toLowerCase())
                 .replace(/QXQXQ/gi, obj.title)
                ).click(function() { OnArticleListChange(this, node, context); });
        $(listDiv).append(item);
    });
    //Empty row at the end of the list for proper scrolling
    var item = itemTemplate.replace('display:none', '').replace(/XQXQX/gi, 'A').replace(/QXQXQ/gi, '&nbsp;');
    $(listDiv).append(item);
    //Scroll smothlly to reach target item
    //context.ID = 4668;
    if (node.nodes.length > 0) {
        var itemID = '#itemID_' + (context.ID == -1 ? node.nodes[0].url : context.ID);
        $(listDiv).scrollTo(itemID, 3000, { offset: 0 });
        $(itemID, listDiv).focus().click();
    }
}


//function OnArticleListChange(selectElement, node, context) {
//    //Display selected item from the list of articles
//    $(selectElement).disable();
//    ContentService.Articl(parseInt(selectElement.value), context.title, function(article) {
//        $('#dataPlace').html(article.content);
//        $(selectElement).enable(); //enable <select> after filling dataPlace
//    },
//                function(error) {
//                    $('#dataPlace').html(error);
//                    $(selectElement).enable();
//                });
//}
//function OnArticleListAdd(selectElement, node, context) {
//    //Insrert all items in the list .. as ... options elements
//    $.each(node.nodes, function(id, obj) {
//        var optionElement = $('<option></option>').attr({ value: $.trim(obj.url).toLowerCase() }).html(obj.title);
//        $(selectElement).append(optionElement);
//    });
//    if (node.nodes.length > 0)
//        $(selectElement).val(context.ID == -1 ? node.nodes[0].url : context.ID).change();
//}
//---------------------------------------------------------
//  HTML files Content
//---------------------------------------------------------
function articl(id, dialogTitle, w, h) {
    var context = { width: w, height: h };
    ContentService.Articl(id, (dialogTitle ? dialogTitle : ""), OnArticleComplete, OnContentError, context);
    return false;
}
function articlefile(htmlName, dialogTitle, location, w, h) {
    var context = { width: w, height: h };
    ContentService.GetDoc(htmlName, (dialogTitle ? dialogTitle : ""), location == 'dialog' ? OnArticleComplete : OnContentComplete, OnContentError, context);
    return false;
}

function OnArticleComplete(results, context, methodname) {
    if (!results || results == "") {
        alert("غير متاح");
        return;
    }
    var myBody = $('<div id="hajjContent"></div>')
    .html(results.content);
    context.width = (typeof context.width == 'undefined') ? 400 : context.width;
    context.height = (typeof context.height == 'undefined') ? 200 : context.height;
    showDialog(results.title, myBody, context.width, context.height, false, true, null, function() { $(myBody).remove(); });
}

//---------------------------------------------------------
//  Articls and news Content
//---------------------------------------------------------
function LoadContent(id, type, leaf, templateName, htmlTemplate) {
    //templateName: is the name of a template exist in a Afaq database
    //But htmlTemplate: is html elements that can be in oDevContentTemplate
    //you can path oDevContentTemplate in htmlTemplate
    //oDevContentTemplate can be loaded while invoking of InitFunctions using:
    //AddPreHackChain('LoadTemplate("tempDevID")') or AddPostHackChain('LoadTemplate("tempDevID")')
    var context = { htmlTemplate: '' };
    if (!(typeof htmlTemplate == 'undefined' || htmlTemplate == ''))
        context.htmlTemplate = htmlTemplate;
    //
    templateName = ((typeof templateName == 'undefined') ? "" : templateName);
    ContentService.GetContent(id, type, leaf, templateName, OnContentComplete, OnContentError, context);
    return false; //Suspend default action of button, anchor ... etc
}

function OnContentComplete(results, context, methodname) {
    var title = (typeof context.title == 'undefined' || context.title == '') ? results.title : context.title;
    var template = (typeof context.htmlTemplate == 'undefined' || context.htmlTemplate == '') ? results.template : context.htmlTemplate;
    ShowContent(results.content, title, false, contentAnimationID, template);
}
//---------------------------------------------------------
//  General operations associated with content
//---------------------------------------------------------
function OnContentError(result) {
    alert("AWQAF: Content Error: " + result);
    //PlayMarque(true);
}

function emailCheck(str) {

    var at = "@";
    var dot = ".";
    var lat = str.indexOf(at);
    var lstr = str.length;
    var ldot = str.indexOf(dot);
    if (str.indexOf(at) == -1) {
        return false;
    }

    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false;
    }

    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false;
    }

    if (str.indexOf(at, (lat + 1)) != -1) {
        return false;
    }

    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false;
    }

    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false;
    }

    if (str.indexOf(" ") != -1) {
        return false;
    }

    return true;
}

function addfav(title) {
    if (document.all) {
        window.external.AddFavorite("http://hajj.gov.qa", title);
    }
}
function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

//---------------------------------------------------------
//  Books list view
//---------------------------------------------------------
function OnBooksComplete(results, context, methodname) {
    $('#' + context.section.divID).html(results);
}
//---------------------------------------------------------
//  Fatwa Content
//---------------------------------------------------------
var fatwaCall = "";
var FatwaLeafID = -1;
function Fatwa(call, arg0, arg1, arg2, onSucess, title, htmlTemplate) {
    fatwaCall = call;
    switch (call) {
        case "init":
            {
                FatwaLeafID = arg2;
                var context = { OnFatwaSucess: onSucess, htmlTemplate: '', title: '' };
                if (!(typeof title == 'undefined' || title == ''))
                    context.title = title;
                if (!(typeof htmlTemplate == 'undefined' || htmlTemplate == ''))
                    context.htmlTemplate = htmlTemplate;
                //LeafID must not be joined to any Fatwa, in order to view correct tree and breadcrumbs
                ContentService.FatwaInit(arg0, arg1, arg2, OnInitFatwaComplete, OnContentError, context);
            } break;
        case "searchhits":
            {
                ContentService.GetFatwaSearchHits(FatwaLeafID, arg0, arg1, OnFatwaContentComplete, OnContentError);
                fatwaCall = "hitslist";
            } break;
        case "tree":
            {
                ContentService.GetFatwaTree(arg0, OnFatwaContentComplete, OnContentError);
            } break;
        case "hitslist":
            {
                ContentService.GetFatwaHitsList(arg0, OnFatwaContentComplete, OnContentError);
            } break;
        case "body":
            {
                ContentService.GetFatwaBody(arg0, OnFatwaContentComplete, OnContentError);
            } break;
        case "breadcrumbs":
            {
                ContentService.GetFatwaBreadcrumbs(arg0, OnFatwaContentComplete, OnContentError);
            } break;
    }
    return false;
}

function OnRandomFatwaComplete(results, context, method) {
    //alert(results);
    if (checkElementID(context.section.divID)) {
        var fatwaContext = $('#' + context.section.divID).html(results);
    }
}
function OnInitFatwaComplete(results, context, method) {
    OnContentComplete(results, context, method);
    if (typeof context.OnFatwaSucess != 'undefined')
        context.OnFatwaSucess();
}
function OnFatwaContentComplete(results, context, methodname) {
    var zone = "#ctl00_" + fatwaCall + "ZoneInFatwa";
    $(zone).html(results);
}
//---------------------------------------------------------
//  Media (Audio/Vedio) Content
//---------------------------------------------------------
var OMediaList = {}; //A list of objects of kind O_xxx. Like O_123 and O_124.
//Each object of kind O_xxx will contain attributes like leafID, divID, templates and mediaList.
; $(function() {
    $.fn.media.mapFormat('mp3', 'winmedia');
    $.fn.media.mapFormat('flv', 'winmedia');
    $.fn.media.mapFormat('mp4', 'winmedia');
});

function OnMediaError(error) {
    alert("Media: " + error);
}
function OnMediaComplete(results, context, methodname) {
    //Declare and then define O_xxx objects, where xxx is the leafID i.e. O_123, O_124 
    var obj = 'OMediaList.O_' + context.section.leafID;
    //define the new add object O_xxx
    eval(obj + ' = {};');
    //keep track of section information provided by Initialization manager
    eval(obj + '.section = context.section;');
    //the following variables are being kept for fast access and later use
    eval(obj + '.leafID = context.section.leafID;');
    eval(obj + '.divID = context.section.divID;');
    //Keep track of program-unit templates
    eval(obj + '.templates = results.templates;');
    //Keep track of media files list associated with provided section
    eval(obj + '.mediaList = results.mediaList;');
    //Keep track of subsections associated with provided section
    eval(obj + '.subSections = results.subSections;');
    //prepare a temperory holder for objects of type O_xxx
    var oMedia = {};
    //Use the provided leafID to bring out an object from OMediaList
    eval('oMedia = ' + obj + ';');
    //
    if (oMedia.divID != '') {
        var list = MediaList(oMedia, 4);
        pindAudioClick($('#' + oMedia.divID).html(list));
    }
}

function ShowClassifiedMedia(leafID, isPopup) {
    var oMedia = {}; //temperory holder for objects like O_123, O_124 .. of type O_xxx
    //Use the provided leafID to get single object from media objects
    eval('oMedia = OMediaList.O_' + leafID + ';');
    var myBody = ShowList(oMedia, null, oMedia.section.title, isPopup, OnMediaListAdd, OnMediaListChange);
    //
    //var table = MediaTable(oMedia, 1, 10);
    //var myBody = $(table);
    pindAudioClick(myBody);
    //showDialog('المكتبة الصوتية', myBody, 600, 270, true, false, null, function() { stopAudio(myBody); $(myBody).remove(); });
    return false;
}

function OnMediaListChange(listDiv, oMedia, context) {
    //Display selected item from the list of articles
    $(listDiv).disable();
    //var buf = MediaTable(oMedia, 1, 10, listDiv.value);
    var itemID = $(listDiv).attr('ID');
    itemID = itemID.replace('itemID\_', '');
    var buf = MediaTable(oMedia, 1, 10, itemID);
    //
    pindAudioClick($('#dataPlace').html(buf));
    $(listDiv).enable(); //enable <select> after filling dataPlace
}
function OnMediaListAdd(listDiv, selectElement, oMedia, context) {
    var itemTemplate = $(selectElement).html();
    //Insrert all items in the list .. as ... options elements
    var selID = -1;
    for (var id = 0; id < oMedia.subSections.length; id++) {

        //var optionElement = $('<option></option>').attr({ value: id }).html(oMedia.subSections[id].title);
        var item = $(itemTemplate.replace('display:none', '')
                 .replace(/XQXQX/gi, id)
                 .replace(/QXQXQ/gi, oMedia.subSections[id].title)
                ).click(function() { OnMediaListChange(this, oMedia, context); });

        $(listDiv).append(optionElement);

        if (id == 0) {
            selID = id;
        }
    }
    //if (selID > -1)
    //    $(listDiv).val(selID).change();
    //Empty row at the end of the list for proper scrolling
    var item = itemTemplate.replace('display:none', '').replace(/XQXQX/gi, 'A').replace(/QXQXQ/gi, '&nbsp;');
    $(listDiv).append(item);
    //Scroll smothlly to reach target item
    if (selID > -1) {
        var itemID = '#itemID_' + selID;
        $(listDiv).scrollTo(itemID, 3000, { offset: 0 });
        $(itemID, listDiv).focus().click();
    }
}


function ShowMediaTable(leafID) {
    var oMedia = {}; //temperory holder for objects like O_123, O_124 .. of type O_xxx
    //Use the provided leafID to get single object from media objects
    eval('oMedia = OMediaList.O_' + leafID + ';');
    //
    var table = MediaTable(oMedia, 1, 10);
    var myBody = $(table);
    pindAudioClick(myBody);
    showDialog(oMedia.section.title, myBody, 600, 270, true, false, null, function() { stopAudio(myBody); $(myBody).remove(); });
    return false;
}

function MediaTable(oMedia, pageNo, rowsCount, subSectionID) {
    //this function needs 4 or more templates
    if (oMedia.templates.length < 2)
        return "";
    //
    var table = oMedia.templates[0];
    var row = oMedia.templates[1];
    var link1 = oMedia.templates[2];
    var link2 = oMedia.templates[3];
    //
    var mediaList = (typeof subSectionID == 'undefined') ? oMedia.mediaList : oMedia.subSections[subSectionID].mediaList;
    for (var id = 0; id < mediaList.length; id++) {
        //if (id == rowsCount)
        //    break;
        var r = row;
        r = r.replace(/-TITLE-/gi, mediaList[id].title);
        r = r.replace(/-SPEAKER-/gi, mediaList[id].speaker);
        r = r.replace(/-KIND-/gi, mediaList[id].kind);
        var l1 = link1;
        var l2 = link2;
        l1 = l1.replace(/-HREF-/gi, mediaList[id].listenUrl);
        l2 = l2.replace(/-HREF-/gi, mediaList[id].downloadUrl);
        r = r.replace(/-LISTEN-/gi, l1);
        r = r.replace(/-DOWNLOAD-/gi, l2);
        table = table.replace(/-ROW-/gi, r + '-ROW-');
    }
    table = table.replace(/-ROW-/gi, '&nbsp;');
    return table;
}
function MediaList(oMedia, rowsCount) {
    //this function needs 4 or more templates
    if (oMedia.templates.length < 2)
        return "";
    //
    var list = oMedia.templates[4];
    var row = oMedia.templates[5];
    var more = oMedia.templates[6];
    //
    for (var id = 0; id < oMedia.mediaList.length; id++) {
        if (id == rowsCount)
            break;
        var r = row;
        r = r.replace(/-TITLE-/gi, oMedia.mediaList[id].title);
        r = r.replace(/-HREF-/gi, oMedia.mediaList[id].listenUrl);
        list = list.replace(/-ROW-/gi, r + '-ROW-');
    }
    list = list.replace(/-ROW-/gi, '&nbsp;');
    if (oMedia.mediaList.length > rowsCount) {
        more = more.replace(/-LEAFID-/gi, oMedia.leafID);
        list = list.replace(/-MORE-/gi, more);
    }
    else {
        list = list.replace(/-MORE-/gi, "");
    }
    //
    return list;
}
function pindAudioClick(elem) {
    //Create event click for each anchor in the provided element.
    $.fn.media.defaults.params.stretchToFit = true;
    var withinElem = (typeof elem == 'undefined') ? "body" : elem;
    $('a.media', withinElem).click(function(event) {
        event.preventDefault();
        var current = this;
        var body = 'modalBody';
        var mediaPlaceID = 'mediaPlace';
        var bodyElement = '<div id="' + body + '"></div>';
        var mediaPlace = '<BR/><BR/><div id="' + mediaPlaceID + '" align="center" style="height:100px"></div>';
        var size = { w: 300, h: 60 }; //Size of audio dialog
        //
        var myBody = $(bodyElement)
        .attr({ title: '', display: 'none' })
        .append(mediaPlace)
        .find('#' + mediaPlaceID)
            .html(makeMediaAnchor(current.href, $(current).text()))
            .find('a.mymedia')
				.each(function() {
				    //give video more space than audio
				    if (isVedio(current.href)) {
				        size.w = 480; size.h = 375; //Size of vedio dialog
				    }
				})
                .media({ autoplay: true, width: size.w, height: size.h, bgColor: 'transparent' })
            .end()
            .find('div.mymedia')
                .css({ textalign: 'center', color: 'Maroon', cursor: 'default', border: 'solid 0px blue' })
                .find('object:first-child')
                    .attr({ id: 'Player', name: 'Player' })
                .end()
            .end()
        .end();
        //Prevent other audios from being played
        //It may causes bugs for fast clicking on other links
        $('a.media', withinElem).unbind('click');
        $('a.media', withinElem).click(function(event) { event.preventDefault(); });
        //Show dialog slowly, with its customized size
        showDialog('المكتبة الصوتية', myBody, size.w + 50, size.h + 110, false, true, null, function() { stopAudio(myBody); $(myBody).remove(); pindAudioClick(withinElem); });
        $(myBody).find('div.mymedia').show('slow');
    });
}
//The following code is nice, but the upper one is more eigable and more practice.
//additional it has not solved bug
function GetAudiosList(arg) {
    ContentService.AudiosList(arg, OnAudiolistComplete, OnContentError);
    return false;
}
function OnAudiolistComplete(results, context, methodname) {
    showAudioList(results);
}
function showAudioList(results) {
    var caption = 'المكتبة الصوتية';
    var body = 'modalBody';
    var mediaPlaceID = 'mediaPlace';
    var bodyElement = '<div id="' + body + '" style="rtl"></div>';
    var mediaPlace = '<BR/><BR/><div id="' + mediaPlaceID + '" align="center" style="height:100px"></div>';
    //
    var myBody = $(bodyElement)
    .attr({ title: '', display: 'none' })
    .html('<select></select>')
    .append(mediaPlace)
    .find('select:first-child')
    .addClass('optionslist')
    .attr('size', '8')
    .change(function(event) {
        var current = this;
        $(this).disable();
        //stop previouse media if exist
        var player = $($(this).parent()).find('object')[0];
        if (player && player.controls)
            player.controls.stop();
        $($(this).parent())
        .find('#' + mediaPlaceID)
            .html(makeMediaAnchor(this.value, $(this).find('[value*=' + this.value + ']').text()))
            .find('a.mymedia')
                .media({ width: 300, height: 60, bgColor: 'transparent' })
            .end()
            .find('div.mymedia')
                .css({ textalign: 'center', color: 'Maroon', cursor: 'default', border: 'solid 0px blue' })
                .find('object:first-child')
                    .attr({ id: 'Player', name: 'Player' })
                .end()
                .show('slow', function() {
                    $(current).enable();
                }); //end of show
    })//end of change event
    .each(function() {//for each select element .. realy it is only one
        var select = this;
        //retrive list items as ... options
        $.each(results, function(id, obj) {
            var optionElement = $('<option></option>').attr({ value: $.trim(obj.url).toLowerCase() }).html(obj.title);
            $(select).append(optionElement);
        });
    })
    .end();
    showDialog('المكتبة الصوتية', myBody, 500, 260, false, true, null, function() { stopAudio(myBody); $(myBody).remove(); });
}

function PlayMedia(url, w_, h_, divID, caption, inDialog) {//, extension, player
    //validate
    if (typeof url == 'undefined')
        return;
    //Init
    //winmedia, quicktime, flash
    $.fn.media.mapFormat('mp3', 'winmedia');
    $.fn.media.mapFormat('flv', 'winmedia');
    $.fn.media.mapFormat('mp4', 'winmedia');
    //$.fn.media.mapFormat(extension, player);
    $.fn.media.defaults.params.stretchToFit = true;
    //continue init wih defaults
    var size = { w: 300, h: 60 }; //Size of audio dialog
    size.w = (typeof w_ == 'undefined') ? 300 : w_;
    size.h = (typeof h_ == 'undefined') ? 60 : h_;
    inDialog = (typeof inDialog == 'undefined') ? true : inDialog;
    divID = ((typeof divID == 'undefined') || (inDialog)) ? '<div id="modalBody"></div>' : ('#' + divID);
    caption = (typeof caption == 'undefined') ? '' : caption;
    //Play
    var myBody = $(divID)
	.attr({ title: '', display: 'none' })
	.append('<BR/><BR/><div id="mediaPlace" align="center" style="height:100px"></div>')
	.find('#mediaPlace')
		.html(makeMediaAnchor(url, ''))
		.find('a.mymedia')
			.media({ autoplay: true, width: size.w, height: size.h, bgColor: 'transparent' })
		.end()
		.find('div.mymedia')
			.css({ textalign: 'center', color: 'Maroon', cursor: 'default', border: 'solid 0px blue' })
			.find('object:first-child')
				.attr({ id: 'Player', name: 'Player' })
			.end()
		.end()
	.end();
    //Show dialog slowly, with its customized size
    if (inDialog)
        showDialog(caption, myBody, size.w + 50, size.h + 110, false, true, null, function() { stopAudio(myBody); $(myBody).remove(); });
    $(myBody).find('div.mymedia').show('slow');
}

//---------------------------------------------------------
//  miceleinous
//---------------------------------------------------------
//---------------------------------------------------------
//  ::  private members .. not allowed for users
//---------------------------------------------------------
var oListHTML = ''; //template to display a list of items with detail view
function ShowList(param1, param2, caption, isPop, OnListAdd, OnListChange) {
    //the content may displayed on dialog "popup" or on current page surface
    var bodyElement = isPop ? oListHTML : ShowContent(oListHTML, caption);
    
//    var myBody = $(bodyElement)
//    .attr({ title: '', display: 'none' })
//    .find('select:first')
//        .addClass('optionslist')
//        .attr('size', '10')
//        .change(function(event) { OnListChange(this, param1, param2); })//call OnListChange when change event occures
//        .each(function() { OnListAdd(this, param1, param2); })//call OnListAdd for each select element, realy it is only one.
//    .end();

    var myBody = $(bodyElement).attr({ title: '', display: 'none' });
    OnListAdd($('#listDiv', myBody), $('#listItemTemplate', myBody), param1, param2); //call OnListAdd for each select element, realy it is only one.
    //$('#listDiv div', myBody).click(function(){ OnListChange(this, param1, param2); });//call OnListChange when change event occures
    if (isPop)
        showDialog(caption, myBody, 600, 500, false, true, null, function() { $(myBody).remove(); });
    return myBody;
}

//---------------------------------------------------------
//  ::  public members .. allowed for users
//---------------------------------------------------------
var frameRunning = false;
var lastFrameID = '';
function openiniframe(idName, url, scrollYesNo, w, h, title, preventHideEvent, htmlTemplate) {
    //you can use tempalte by pathing oDevContentTemplate in htmlTemplate
    //oDevContentTemplate can be loaded while invoking of InitFunctions using:
    //AddPreHackChain('LoadTemplate("tempDevID")') or AddPostHackChain('LoadTemplate("tempDevID")')
    if (frameRunning && lastFrameID == idName)
        return false;
    scrollYesNo = (scrollYesNo == null || (typeof scrollYesNo == 'undefined') || scrollYesNo == "" || scrollYesNo == "NaN") ? "no" : scrollYesNo;
    w = (w == null || (typeof w == 'undefined') || w == "" || w == "NaN") ? "100%" : w;
    h = (h == null || (typeof h == 'undefined') || h == "" || h == "NaN") ? "400" : h;
    title = (title == null || (typeof title == 'undefined') || title == "" || title == "NaN") ? "" : title;
    var sHtml = '<iframe Id="' + idName + '" name="' + idName + '" width="' + w + '" height="' + h + '" scrolling="' + scrollYesNo + '" marginwidth="0"  marginheight="0" frameborder="0" allowtransparency="true" src="' + url + '"></iframe>';
    if (typeof htmlTemplate == 'undefined' || htmlTemplate == '')
        ShowContent(sHtml, title);
    else
        ShowContent(sHtml, title, false, contentAnimationID, htmlTemplate); //use temaplate
    //Latch flage for single frame, so any frame else will work normally on dialog
    if (!frameRunning) {
        frameRunning = (typeof preventHideEvent == 'undefined') ? frameRunning : preventHideEvent;
        lastFrameID = idName;
    }
    return false;
}

// function openiniframe(idName, url, scrollYesNo) {
// scrollYesNo = (scrollYesNo == null || (typeof scrollYesNo == 'undefined') || scrollYesNo == "" || scrollYesNo == "NaN") ? "no" : scrollYesNo;
// var sHtml = '<iframe Id="' + idName + '" name="awqaf" width="100%" height="400" scrolling="' + scrollYesNo + '" marginwidth="0"  marginheight="0" frameborder="0" src="' + url + '"></iframe>';
// ShowContent(sHtml, "");
// return false;
// }

function openindialog(idName, url, title, w, h) {
    var myBody = $('<div id="temp_dialog"></div>')
        .html('<iframe Id="' + idName + '" name="' + idName + '" width="' + w + '" height="' + h + '" scrolling="no" marginwidth="0"  marginheight="0" frameborder="0" src="' + url + '"></iframe>');
    var dialog;
    showDialog(title, myBody, w ? w + 50 : 650, h ? h + 110 : 480, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
    return false;
}

function openDevInDialog(devID, title, w, h, html) {
    var htmlBuf = '';
    if (typeof html != 'undefined' && html != '') {
        htmlBuf = html;
    }
    else
        htmlBuf = $('#' + devID).html();
    var myBody = $('<div id="temp_dialog"></div>')
        .html(htmlBuf);
    var dialog;
    showDialog(title, myBody, w ? w + 50 : 650, h ? h + 110 : 480, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
    return false;
}

function SetiFrameHeight(idName, mainElementID, tolerance) {
    if (typeof tolerance == 'undefined')
        tolerance = 0;
    $('#' + idName).height($('#' + idName).contents().find('#' + mainElementID + '').height() + tolerance);
}

function expandcontent(cid) {
    $('#' + cid).toggleClass('switchcontentshow').toggleClass('switchcontent');
}

var contentAnimationID = 0;
function CloseContent() {
    $("#contentPlace").css({ display: "none", visibility: "hidden" });
    $("#contentSubBody").hide().html("empty");
    $("#contentMainBody").show(contentAnimationID == 0 ? "" : "slow");
    PlayMarque(true);
    DisplayBanners();
    DisplaySurvays();
    //
    frameRunning = false;
    //Return back default template to ensure stability of all programable-units functionality
    UseTemplate(oDefaultContentTemplate);
}

function ShowContent(sHtml, sTitle, allowTitle, animationID, otherTemplate) {
    if (frameRunning) {
        var myBody = $(sHtml);
        showDialog(sTitle, myBody, 800, 600, true, false, null, function() { $(myBody).remove(); });
        return;
    }
    var template = ((typeof otherTemplate == 'undefined' ||
                        otherTemplate == 'NaN' ||
                        otherTemplate == '' ||
                        otherTemplate == null) ? oDefaultContentTemplate : otherTemplate);
    UseTemplate(template);
    //contentPlace:
    //  It is the first container/<div>element of all elements used to show and animate provided-content (sHTML)
    //  It exists in ContentPlace web-user-control, or any given template, just to hide complexity away of the graphic designer
    //contentSubBody:
    //  Its place is above contentMainBody inside contentPlace
    //  It is the container of the requersted content, 
    //  it will be showed slowlly after filling it with requested content
    //contentMainBody:
    //  It is the container of the original content delivered with master page
    //  This original content will be hide to leave displaying space for the requested content
    //contentHeadTitle:
    //  It is the title if requsted content
    //Allow title only in case of allowTitle==true
    if ((typeof allowTitle == 'undefined') || allowTitle == false)
        $('.ui-s-dialog-titlebar').css({ display: "none", visibility: "hidden" });
    //Set animation id that will used by default for future animations
    contentAnimationID = (typeof animationID == 'undefined') ? contentAnimationID : animationID;
    //Animate and view content
    switch (contentAnimationID) {
        case 0:
            {
                $("#contentSubBody").hide();
                $("#contentMainBody").hide();
                $("#contentPlace").css({ display: "block", visibility: "visible" });
                $("#contentHeadTitle").html(sTitle);
                $("#contentSubBody").html(sHtml).show();
            } break;
        case 1:
            {
                $("#contentSubBody").hide("fast");
                $("#contentMainBody").hide();
                $("#contentPlace").css({ display: "block", visibility: "visible" });
                $("#contentHeadTitle").html(sTitle);
                $("#contentSubBody").html(sHtml).show("slow");
            } break;
    }
    DisplayBanners();
    DisplaySurvays();
    //return the parent of the given HTML to allow operation chaining
    return $("#contentSubBody");
}

function showDialog(myTitle, myBody, w, h, modal, sizeable, openFn, closeFn) {
    var dialogElement = '<div id="dialog" class="flora" title=""></div>';
    $(dialogElement).append(myBody).dialog(
    {
        show: 'slow',
        hide: 'slow',
        resizable: sizeable ? sizeable : false,
        title: '<span style="direction:rtl;padding:0px 10px 0px 10px;float:left">' + (myTitle ? myTitle : "Hi!") + '</span>',
        height: h ? h : 260,
        width: w ? w : 500,
        modal: (modal != null) ? modal : true,
        dialogClass: 'base',
        overlay: { opacity: 0.7, background: "black" },
        autoOpen: true,
        bgiframe: true,
        open: function(type, data) {
            //I don't know why I must add some pxels on 
            //the height of 'ui-dialog' to display the upper boundary of the dialog !!!!!!!!!!!!!
            $(this).parent().parent().css({ height: h + 800 + 'px' });
            if (openFn)
                openFn.call(this);
            //$(this).text($(this).parent().html());
        },
        close: function(type, data) {
            if (closeFn)
                closeFn.call(this);
            $(this).hide('slow', function() { $(this).remove() });
        }
    });
}
function stopAudio(myBody) {
    var player = $(myBody).find('object')[0];
    if (player && player.controls)
        player.controls.stop();
}
function isVedio(href) {
    var vedios = ['asx', 'asf', 'avi', 'wmv', 'rpm', 'rv', 'flv', 'swf', 'mov', 'mpg', 'mpeg', 'mp4'];
    var arr = href.split('.');
    return ($.inArray(arr[arr.length - 1], vedios) != -1);
}
function makeMediaAnchor(href, text, w, h) {
    var anchor = '<style>.mymedia{display:none;}</style>';

    href = href.toLowerCase();
    var arr = href.split('.');
    if (arr.length <= 0) return '';
    var images = ['gif', 'jpg', 'png', 'bmp', 'tif'];

    if ($.inArray(arr[arr.length - 1], images) != -1) {

        anchor += '<img class="mymedia" src="' +
                    href +
                    '" width="' +
                    w +
                    '" height="' +
                    h +
                    '">' +
                    text +
                    '</img>';
    }
    else {
        anchor += '<a class="mymedia" style="display:none" href="';
        anchor += href;
        anchor += '">';
        anchor += text;
        anchor += '</a>';
    }
    return anchor;
}

function navigatorInfo() {
    alert('navigator.appVersion: ' + navigator.appVersion);
    alert('navigator.userAgent: ' + navigator.userAgent);
    alert('navigator.appName: ' + navigator.appName);
    alert('navigator.appCodeName: ' + navigator.appCodeName);
    alert('navigator.cookieEnabled: ' + navigator.cookieEnabled);
    alert('navigator.language: ' + navigator.language);
    alert('navigator.mimeTypes: ' + navigator.mimeTypes[0]);
    alert('navigator.platform: ' + navigator.platform[0]);
    alert('navigator.plugins: ' + navigator.plugins);
    alert('navigator.systemLanguage: ' + navigator.systemLanguage);
    alert('navigator.userLanguage: ' + navigator.userLanguage);
}
//----------------------------------------------------------------------
//var islamicFinder_url = "http://www.islamicfinder.org/prayer_service.php?country=Qatar&city=Doha &latitude=25.2867&longitude=51.5333&lang=arabic&state=01&zipcode=&calculate=1&dayLight=0&HanfiShafi=1&pmethod=4&timezone=3.00&dhuhrInterval=1&maghribInterval=1&fajrTwilight1=10.00&ishaTwilight=10.00&fajrTwilight2=10.00&ishaInterval=30";
//Javascrpt is not allowed to access external domains .. security message will emerge
//function getIslamicFinderTimes(divID, isHorz) {
//    var timesID = '#' + divID;
//	$(timesID).html('<div id="wait" style="vertical-align:middle;text-align:center;font-size:14px;display:none">جاري تحميل مواقيت الصلاة</div>')
//	.find('#wait')
//	    .show('slow',function(){
//	        $.ajax({
//	            type: 'GET',
//	            url: islamicFinder_url,
//	            dataType: 'html',
//	            success: function(data, textStatus, oXmlHttpRequest){
//		            if(textStatus != 'success')
//			            return;
//		            $(timesID).html(render(data,isHorz));
//		            //wakeup();
//	            },
//	            error: function(XMLHttpRequest, textStatus, errorThrown){
//		            $(timesID).html('<div style="text-size:8px"></div>');
//	            }	
//	        });
//	    });
//}
function OnPrayerTimesDataComplete(results, context, method) {
    results = "<div>" + results + "</div>";
    var timesID = '#' + context.section.divID;
    var isHorz = context.isHorz;
    $(timesID).html('<div id="wait" style="vertical-align:middle;text-align:center;font-size:14px;display:none"></div>')
	.find('#wait')
	.show('slow', function() {
	    $(timesID).html(render(results, isHorz));
	});
}
function render(data, isHorz) {
    var dataDom = $(data);
    var str = '<table dir=rtl border=0 bordercolor="transparent" cellspacing=0 cellpadding=0>';
    str = isHorz ? '' : str;
    $('td', dataDom).each(function(id) {
        str += isHorz ? getHorzString(id, $(this).text()) : getVertString(id, $(this).text());
    });
    str += isHorz ? "" : "</table>";
    return str;
}

function getHorzString(id, html) {
    switch (id) {
        //		case 0://Doha, Qatar    
        //		{    
        //			var tag1 = '<tr><td class="IslamicDataSmall" align="center" valign="middle" colspan=2 dir="ltr">';    
        //            tag1 += '        <img alt="Scroll Left" style="cursor:pointer" id="leftArrow" src="arrowLeft.gif" onmouseover="hrzScroll(2,\'container\',\'content\')"';    
        //            tag1 += '            onmouseout="hrzScroll(0,\'container\',\'content\')" />&nbsp;';    
        //			tag1 += '<div id="container" class="hrzScrollContainer"><div id="content" class="hrzScrollContent">';    
        //			var tag2 = '</div></div>';    
        //            tag2 += '        &nbsp;<img alt="Scroll Right" style="cursor:pointer" id="rightArrow" src="arrowRight.gif" onmouseover="hrzScroll(1,\'container\',\'content\')"';    
        //            tag2 += '            onmouseout="hrzScroll(0,\'container\',\'content\')" />';    
        //			tag2 += '</td></tr>';    
        //			    
        //			return tag1 + html + tag2;		    
        //		}break;    
        case 1: //Hijjery
        case 2: //Milady
            {
                //return '<td class = "IslamicDataSmall" align="center" colspan=2 nowrap>' + html + "</td>";
                return ' <span class="prayDate">' + html + '</span> <span class="praySeprator">|</span> ';
            } break;
        //		case 3://help    
        //		{    
        //			return '';    
        //		}break;    
        //		case 4://day    
        //			html = '<strong>' + html  + '</strong>';    
        //      break;    
        case 5: //day valu
            //html = '<td><strong>' + html  + '</strong><td>';
            return '<span class="prayDay">' + html + '</span><span class="praySeprator">|</span>';
        case 6: //Fajr
        case 8: //Sherouq
        case 10: //Zohr
        case 12: //Aser
        case 14: //Maghreb
        case 16: //Aeshaa
            {
                //return '<td class = "IslamicDataSmall">' + html + "</td>";
                return ' <span class="prayTimeTitle">' + html + '</span> ';
            } break;
        case 7: //Fajr time
        case 9: //Sherouq time
        case 11: //Zohr
        case 13: //Aser
        case 15: //Maghreb
        case 17: //Aeshaa
            {
                //var time = 'id="time' + id + '"';
                //return '<td ' + time + ' class = "IslamicDataSmall">' + html + "</td>";
                return ' <span class="prayTime">' + html + '</span> <span class="praySeprator">|</span> ';
            } break;
    }
    return '';
}

function getVertString(id, html) {
    switch (id) {
        case 0: //Doha, Qatar
            {
                var tag1 = '<tr><td class="IslamicDataSmall" align="center" valign="middle" colspan=2 dir="ltr">';
                tag1 += '        <img alt="Scroll Left" style="cursor:pointer" id="leftArrow" src="arrowLeft.gif" onmouseover="hrzScroll(2,\'container\',\'content\')"';
                tag1 += '            onmouseout="hrzScroll(0,\'container\',\'content\')" />&nbsp;';
                tag1 += '<div id="container" class="hrzScrollContainer"><div id="content" class="hrzScrollContent">';
                var tag2 = '</div></div>';
                tag2 += '        &nbsp;<img alt="Scroll Right" style="cursor:pointer" id="rightArrow" src="arrowRight.gif" onmouseover="hrzScroll(1,\'container\',\'content\')"';
                tag2 += '            onmouseout="hrzScroll(0,\'container\',\'content\')" />';
                tag2 += '</td></tr>';

                return tag1 + html + tag2;
            } break;
        case 1: //Hijjery
        case 2: //Milady
            {
                return '<tr><td class = "IslamicDataSmall" align="center" colspan=2 nowrap>' + html + "</td></tr>";
            } break;
        case 3: //help
            {
                return '';
            } break;
        case 4: //day
            html = '<strong>' + html + '</strong>';
        case 6: //Fajr
        case 8: //Sherouq
        case 10: //Zohr
        case 12: //Aser
        case 14: //Maghreb
        case 16: //Aeshaa
            {
                return '<tr><td class = "IslamicDataSmall">' + html + "</td>";
            } break;
        case 5: //day valu
            html = '<strong>' + html + '</strong>';
        case 7: //Fajr time
        case 9: //Sherouq time
        case 11: //Zohr
        case 13: //Aser
        case 15: //Maghreb
        case 17: //Aeshaa
            {
                var time = id != 5 ? 'id="time' + id + '"' : '';
                return '<td ' + time + ' class = "IslamicDataSmall">' + html + "</td></tr>";
            } break;
    }
    return '';
}

//-------------------------------------------
//			Printing
//-------------------------------------------

//Functionality: Preview and Print a part of web page 
//Wael AlGhool: 2011 Mar 27
//Provide this function with a url for a html_template
//The template has to be located in certain folder with its images and css files
//The url provided will be opend in a separte window as preview functionality
//Also provide a div_ID for the area you want to print and place_holder_div_ID inside your template
//This function will take the innerHtml of this div and place it inside your template in place of place holder you provided
function PrintDivWithTemplate_NoPrintDialog_On_IE(printAreaDiv, htmlTemplateUrl, htmlPlaceholderDiv) {
    var pp = window.open(htmlTemplateUrl, 'Print', 'status=0, toolbar=0, menubar=0, resizable=0, scrollbars=1, height=700, width=630  ');
    //Use ajax to timely sync with window.open
    //So, it will be 100% error free to insert/replace data inside DOM_tree of the new window
    $.ajax({
        async: false,
        cache: true,
        data: { key1: 'value1', key2: 'value2' },
        url: htmlTemplateUrl,
        context: document.body,
        success: function(data, textStatus, jqXHR) {
            $('#' + htmlPlaceholderDiv, pp.document).html($('#' + printAreaDiv).html());
        }
    });
}

//This approuach causes error with IE8, it doesn't display print dialog when click over print button
function PrintDivWithTemplate(printAreaDiv, htmlTemplateUrl, htmlPlaceholderDiv) {//, btnToHide) {
    $.ajax({
        async: false,
        cache: true,
        data: { key1: 'value1', key2: 'value2' },
        url: htmlTemplateUrl,
        context: document.body,
        success: function(data, textStatus, jqXHR) {
            var pp = window.open('', 'Print', 'status=0, toolbar=0, menubar=0, resizable=0, scrollbars=1, height=700, width=630  ');
            //pp.location = htmlTemplateUrl; //cause refresh and delay
            pp.document.URL = htmlTemplateUrl;
            pp.document.title = htmlTemplateUrl; //'new title';
            pp.document.writeln(data);
            $('#' + htmlPlaceholderDiv, pp.document).html($('#' + printAreaDiv).html());
        }
    });
}

//Unused function but it is the one I found while diging in the topic of printing
function getPrint2(print_area, btnToHide) {
    var pp = window.open('', 'Print', 'status=0, toolbar=0, menubar=0, resizable=0, scrollbars=1, height=700, width=630  ');
    //Adding HTML opening tag with <HEAD> … </HEAD> portion
    pp.document.writeln('<HTML><HEAD><title>Print Preview</title>' +
                        '<style type="text/css">.hideClass{display:none;}</style>');
    pp.document.writeln('<LINK href=PrintStyle.css  type="text/css" rel="stylesheet" media="print" />');
    pp.document.writeln('<base target="_self"/></HEAD>');
    //Adding Body Tag
    pp.document.writeln('<body MS_POSITIONING="GridLayout" bottomMargin="0" leftMargin="0" topMargin="0" rightMargin="0">');
    //Adding form Tag
    pp.document.writeln('<form  method="post">');
    //Creating two buttons Print and Close within a table
    pp.document.writeln('<TABLE width=100% DIR="RTL"><TR><TD>' +
                        '</TD><TD></TD></TR>' +
                        '<TR><TD align=right>' +
                        '<img src="Images/Common/aprint.gif" id="PRINT" alt="طباعة" style="cursor:pointer" onclick="javascript:location.reload(true);window.print();" />' +
                        '</TD><TD align=left>' +
                        '<img src="Images/Common/delete.jpg" id="CLOSE" alt="Close" style="cursor:pointer" onclick="window.close();" />' +
                        '</TD></TR>' +
                        '<TR><TD></TD><TD></TD></TR></TABLE>');
    //Writing print area of the calling page
    pp.document.writeln($('#' + print_area).html());
    //Ending Tag of </form>, </body> and </HTML>
    pp.document.writeln('</form></body></HTML>');
    //
    $('#' + btnToHide, pp.document).hide();
}

//-------------------------------------------
//Free Counting
//-------------------------------------------
function IncFreeCounter(nickName) {
    ContentService.IncFreeCounter(nickName);
}
function DecFreeCounter(nickName) {
    ContentService.DecFreeCounter(nickName);
}

