﻿function checkElementID(divID) {
    var temp = $('#' + divID).attr('id');
    if (typeof temp == 'undefined')
        return false;
    return true;
}

//---------------------------------------------------------
//Playing marque once DOM-tree is being ready
//---------------------------------------------------------
; $(function() { PlayMarque(true); });

function PlayMarque(enable) {
    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();
    //Exist 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,
    'swing',
    function() {
        $(this).css({ top: '0' });
        //USE SETTIMEOUT .. TO AVOID CALLING STOP() FROM WITHIN CALLBACK
        var timeoutID = setTimeout('PlayMarque(true)', 1000);
        $('#' + marqueName + '_timeout').text(timeoutID);
    });
}
//---------------------------------------------------------
//  Menu handling
//---------------------------------------------------------
; $.fn.getMenuID = function(e) {
    var x = e.pageX - $(this).offset().left;
    var y = e.pageY - $(this).offset().top;
    //
    var h = 27;
    var d = 2;
    var id = Math.floor(y / (h + d));
    var num = (y - (id * (h + d)) - h);
    //1 if mouse within h and 0 if it is out of h
    var bounded = (num & 0x80) >> 7;
    //Binary int to string .. alert(bounded +':, B: ' +bounded.toString(2));
    //Binary string to int .. parseInt('111', 2)
    //Tool tip message .. $(this).attr('alt',e.pageX +'/'+x*bounded + ', ' + e.pageY +'/'+ y*bounded);
    id = (id + 1) * bounded;
    //$(this).attr('alt',id);
    //return 0 means not a correct selection
    return id;
}
;$(function() {
    $('.simpleMenu').each(function() {
        var curMenu = this;
        $('img', $(curMenu))
        .mousemove(function(e) {
            $(this).css('cursor', $(this).getMenuID(e) > 0 ? 'pointer' : 'default');
        })
        .click(function(e) {
            var id = $(this).getMenuID(e);
            if (id > 0) {
                LoadContent(
            parseInt($('#associatedIDs  h1:nth-child(' + id + ')', $(curMenu)).text()),
            parseInt($('#ContentType', $(curMenu)).text()),
            parseInt($('#LeafID', $(curMenu)).text()));
                //$(this).scale().puff();
            }
        });

    });
});

//---------------------------------------------------------
//  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() {
    $(this).animate(
    {
        width: $(this).width() * 2,
        height: $(this).height() * 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
//---------------------------------------------------------
; $(function() {
    //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);
});
function OnBannerClick(sHref) {
    if (sHref.indexOf('javascript:') == 0) {
        eval(sHref.substring(sHref.indexOf(':') + 1, sHref.length));
        return;
    }
    if (sHref != '') {
        window.open(sHref);
        return;
    }
}
var oBanners = {};
function OnBannerComplete(results, context, methodname) {
    $.each(results, function(id, obj) {
        //no banners!
        if (obj.url.length <= 0) return;
        obj.counter = -1;
        obj.display = function(zone) {
            ++zone.counter;
            if (zone.counter >= zone.url.length)
                zone.counter = 0;

            $('#' + zone.banner)
            .each(function() { stopAudio($(this)); })
            .html(makeMediaAnchor(zone.url[zone.counter], '', $('#' + zone.banner).width(), $('#' + zone.banner).height()))
            .find('a.mymedia')
                .media({
                autoplay: true,
                width: $('#' + zone.banner).width(),
                height: $('#' + zone.banner).height(),
                bgColor: 'transparent'
            })
            .end()
            .find('div.mymedia')
                .show()
                .click(function() { if (zone.href[zone.counter] != '') window.open(zone.href[zone.counter]); })
			.end()
            .find('img.mymedia')
                .show()
                .click(function() { OnBannerClick(zone.href[zone.counter]); })
                .css({ cursor: 'pointer' })
            .end();
            //$('div[id^=LeafID_banners]').show().text($('#' + zone.banner).html());
            if (zone.duration[zone.counter] <= 0)
                zone.duration[zone.counter] = 5;
            setTimeout(function() { zone.display(zone) }, zone.duration[zone.counter] * 1000);
            //save zone for later use
            eval('oBanners.' + zone.banner + '=zone;');
            //
        };
        //start object recursion or what can be called a self refrencing technique
        obj.display(obj);
    });
}
function DisplayBanners() {
    for (var zone in oBanners) {
        if (typeof oBanners[zone] == 'undefined')
            continue;
        oBanners[zone].display(oBanners[zone]);
    }
}
function OnBannerError(result) {
}
//---------------------------------------------------------
//  Hamalat Info dialog
//---------------------------------------------------------
function LoadHamalatInfo(lang) {
    StatisticsService.GetHamalatInfo(lang, OnHamalatComplete, OnContentError);
}

function OnHamalatComplete(results, context, methodName) {
    var myBody = $(results.table);
    showDialog(results.title, myBody, 600, 450, false, true, null);
}

//---------------------------------------------------------
//  Statistics dialog
//---------------------------------------------------------
function LoadStcOptions(callBack) {
    if (!window.stcOptions)
        StatisticsService.GetOptions(OnStcOptionsComplete, OnContentError, callBack);
    else {
        callBack();
    }
}
function OnStcOptionsComplete(results, context, methodName) {
    window.stcOptions = results;
    context();
}
; $(function() {
    $('a[class^=stcLink]').each(function() {
        $(this).click(function(event) {
            event.preventDefault();
            var current = this;
            LoadStcOptions(function() {
                var myClass = $(current).attr('class');
                switch (myClass) {
                    case 'stcLink1':
                        {
                            var myBody = $(stcOptions.hamalat).find('#year').text(stcOptions.years[stcOptions.curYear].ID).end();
                            //select year
                            $.each(stcOptions.years, function(id, obj) { $('select:first', myBody).append('<option value="' + id + '">' + obj.ID + '</option>'); });
                            $('select:first', myBody).val(stcOptions.curYear).change(function(event) {
                                var id = $(this).val();
                                StatisticsService.GetTrips(stcOptions.years[id].ID, -1, function(results) {
                                    window.stcOptions.trips = results;
                                    stcOptions.curYear = id;
                                    $('#year', myBody).text(stcOptions.years[id].ID);
                                    tripstable(myBody);
                                });
                            });
                            //display current year
                            tripstable(myBody);
                            showDialog('الإحصاءات', myBody, 600, 450, false, true, null);
                        } break;
                    case 'stcLink2':
                    case 'stcLink3':
                        {
                            var myBody = $(stcOptions.hojjaj).find('#year').text(stcOptions.years[stcOptions.curYear].ID).end();
                            //select year
                            $.each(stcOptions.years, function(id, obj) { $('select[id=years]', myBody).append('<option value="' + id + '">' + obj.ID + '</option>'); });
                            $.each(stcOptions.nations, function(id, obj) { $('select[id=nations]', myBody).append('<option value="' + obj.ID + '">' + obj.Title + '</option>'); });
                            if (myClass == 'stcLink2')
                                stcOptions.curNation = 82; //Qatar
                            else
                                stcOptions.curNation = 115; //Misr
                            $('#nation', myBody).text($('select[id=nations] option[value=' + stcOptions.curNation + ']', myBody).text());
                            $('select[id=nations]', myBody).val(stcOptions.curNation).change(function(event) {
                                var id = $(this).val();
                                var current = this;
                                StatisticsService.GetTrips(stcOptions.years[stcOptions.curYear].ID, id, function(results) {
                                    window.stcOptions.trips = results;
                                    stcOptions.curNation = id;
                                    $('#nation', myBody).text($('[value=' + id + ']', current).text());
                                    tripstable2(myBody);
                                });
                            });
                            $('select[id=years]', myBody).val(stcOptions.curYear).change(function(event) {
                                var id = $(this).val();
                                StatisticsService.GetTrips(stcOptions.years[id].ID, stcOptions.curNation, function(results) {
                                    window.stcOptions.trips = results;
                                    stcOptions.curYear = id;
                                    $('#year', myBody).text(stcOptions.years[id].ID);
                                    tripstable2(myBody);
                                });
                            }).change();
                            //display current year
                            //tripstable2(myBody);
                            showDialog('الإحصاءات', myBody, 600, 450, false, true, null);
                        } break;
                }
            });
        });
    });
});
function tripstable(myBody) {
    $('table tr:not(:first)', myBody).remove();
    $.each(stcOptions.trips, function(id, obj) {
        $('table', myBody).append(
                                '<tr><td>' +
                                (id + 1) +
                                '</td>' +
                                '<td>' +
                                 obj.Title +
                                '</td>' + '<td>' + obj.Summary + '</td><td>' +
                                obj.OfficeTel + '</td><td>' +
                                (obj.Address ? obj.Address : '-') + '</td><td>' +
                                obj.HojjajCount + '</td></tr>'); //Contrname, Address, OfficeTel, Mobile, Fax
    });
    $(myBody).find('tr:first td').addClass('price').end().find('tr:not(:first) td').addClass('border8').end();
}
function tripstable2(myBody) {
    $('table tr:not(:first)', myBody).remove();
    var total = 0;
    $.each(stcOptions.trips, function(id, obj) {
        total += obj.HojjajCount;
        if (obj.HojjajCount > 0)
            $('table', myBody).append(
                                '<tr>'
                                + '<td>' + (id + 1) + '</td>'
                                + '<td>' + obj.Title + '</td>'
                                + '<td>' + obj.HojjajCount + '</td>'
                                + '<td class="percentTemp" hajjcount="' + obj.HojjajCount + '"></td>'
                                + '<td><div class="percentTemp1 percentR"></div><div class="percentTemp2 percentL"></div></td>'
                                + '</tr>'); //Contrname, Address, OfficeTel, Mobile, Fax
    });
    $('#totalCount', myBody).text(total);
    $('td.percentTemp', myBody).each(function() {
        var percent = ($(this).attr('hajjcount') / total) * 100.0;
        var w1 = 200 * (percent / 100);
        var w2 = 200 - w1;
        $(this)
        .text(CurrencyFormatted(percent))
        .next()
        .find('div.percentTemp1')
            .css({ width: w1 + 'px', height: '10px', backgroundColor: 'blue' })
        .end()
        .find('div.percentTemp2')
        .css({ width: w2 + 'px', height: '10px' });
    });
    $(myBody).find('tr:first td').addClass('price').end().find('tr:not(:first) td').addClass('border8').end();
}
//---------------------------------------------------------
//  Audio Content
//---------------------------------------------------------
; $(function() { $.fn.media.mapFormat('mp3', 'winmedia'); pindAudioClick() });
function pindAudioClick() {
    $('a.media').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();
        $('a.media').unbind('click');
        $('a.media').click(function(event) { event.preventDefault(); });
        showDialog('المكتبة الصوتية', myBody, size.w + 50, size.h + 110, false, true, null,
        function() { stopAudio(myBody); setTimeout('function(){$(myBody).remove(); pindAudioClick();}', 25); });
        $(myBody).find('div.mymedia').show('slow');
    });
}
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 + '"></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, 700, 330, false, true, null,
    function() { stopAudio(myBody); setTimeout('function(){$(myBody).remove();}', 25); });
}

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 showDialog(myTitle, myBody, w, h, modal, sizeable, openFn, closeFn) {
    var dialogElement = '<div id="dialog" 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() });
        }
    });
}
//---------------------------------------------------------
//  Survay Content
//---------------------------------------------------------
var survaySelection = -1;
var survayQuestionID = -1;
; $.fn.CloseDialog = function() { $('.ui-dialog-titlebar-close', $(this).parent()).click().attr('class'); };
;$(function() {
    survayQuestionID = $("#survayQuestionID").attr("value");
    //
    $("input.survayRadio").click(function() { survaySelection = this.value; });
    //
    $("img.survayVote").click(function() {
        
        if (survaySelection == -1) {
            alert("برجاء اختيار أحد الأجوبة أولا");
            return;
        }

        SurvayVotting('use cookie', survayQuestionID, survaySelection);
        $("img.survayVote").hide();        

        //var dialog;
        //var myBody =
        //    $('<div id="survayDlg"></div>')
        //    .html($("div#survayDialogs div:first-child").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);
                    //$("img.survayVote").hide();
                    //if (dialog) {
                    //    $(dialog).CloseDialog();
                    //}
         //       })
         //   .end();
        //showDialog("أدخل عنوان بريدك الإلكتروني", myBody, 300, 100, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
    });
    //
    $("img.survayResult").click(function() { SurvayResult(survayQuestionID); });
});
function SurvayVotting(email, questionID, answerID) {
    ContentService.Vote(email, questionID, answerID, OnCompleteSurvayVotting, OnContentError);
}
function SurvayResult(questionID) {
    ContentService.VoteResult(questionID, OnCompleteSurvayVotting, OnContentError);
}
function OnCompleteSurvayVotting(results, context, methodname) {
    var myBody =
            $('<div id="survayReport"></div>')
            .html($("div#survayDialogs div:nth-child(2)").html())
            .find('table:first-child tbody')
                .append("<tr><td colspan='4' align='center'>" + $("#survayQuestion").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, 700, 250, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
}
//---------------------------------------------------------
//  Books Content
//---------------------------------------------------------
function GetBooksList(arg) {
    ContentService.BooksList(arg, OnBooklistComplete, OnContentError);
    return false;
}

function OnBooklistComplete(results, context, methodname) {
    var myBody = $('<div></div>')
    .append('<select></select>')
    .find("select:first-child")
        .attr({ size: "8" })
        .addClass('optionslist')
        .change(function() {
        window.open(this.value, "Read It Now", "width=600,height=400");
    })
        .each(function() {
        var current = this;
        $.each(results, function(id, obj) {
            var option = "<option value=\"" + obj.url + "\">" + obj.title + "</option>";
            $(current).append(option);
        })
    })
    .end()
    .append('<div style="text-align:center;color:red;vertical-align:middle;direction:rtl">اختر الكتاب لتقرأه بعد تنزيله.</div>');
    showDialog("المكتبة المقروءة", myBody, 500, 250, false, true, null, function() { $(myBody).remove(); });
}
//---------------------------------------------------------
//  Articles Content
//---------------------------------------------------------
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, OnContentError, context);
    return false;
}

function OnArticlelistComplete(node, context, methodname) {
    oListHTML = node.html;
    ShowList(node, context, context.title, context.isPop, OnArticleListAdd, OnArticleListChange);
}

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();
}

//---------------------------------------------------------
//  Fatwa Content
//---------------------------------------------------------
var fatwaCall = "";
function Fatwa(call, arg0, arg1, arg2) {
    fatwaCall = call;
    switch (call) {
        case "init":
            {
                ContentService.FatwaInit(arg0, arg1, arg2, OnContentComplete, OnContentError);
            } break;
        case "searchhits":
            {
                ContentService.GetFatwaSearchHits(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 OnFatwaContentComplete(results, context, methodname) {
    var zone = "#ctl00_" + fatwaCall + "ZoneInFatwa";
    $(zone).html(results);
}

//---------------------------------------------------------
//  HTML files Content
//---------------------------------------------------------
function articl(id, dialogTitle) {
    ContentService.Articl(id, (dialogTitle ? dialogTitle : ""), OnHajContentComplete, OnContentError);
    return false;
}
function haj(htmlName, dialogTitle) {
    ContentService.GetDoc(htmlName, (dialogTitle ? dialogTitle : ""), OnHajContentComplete, OnContentError);
    return false;
}

function OnHajContentComplete(results, context, methodname) {
    if (!results || results == "") {
        alert("غير متاح");
        return;
    }
    var myBody = $('<div id="hajjContent"></div>')
    .html(results.content);
    showDialog(results.title, myBody, 400, 250, false, true, null, function() { $(myBody).remove(); });
}

//---------------------------------------------------------
//  Articls and news Content
//---------------------------------------------------------
function LoadContent(id, type, leaf) {
    PlayMarque(false);
    ContentService.GetContent(id, type, leaf, OnContentComplete, OnContentError);
    return false; //Suspend default action of button, anchor ... etc
}

function OnContentComplete(results, context, methodname) {
    //$("#contentSubBody").hide("fast");
    //$("#contentMainBody").hide();
    //$("#contentPlace").css({ display: "block", visibility: "visible" });
    //$("#contentHeadTitle").html(results.title);
    //$("#contentSubBody").html(results.content).show("slow"); //+ '<a href="#"><img src="images/hajj3020.gif" width="90" height="26" border="0" onClick="window.print();"></a>'
    ShowContent(results.content, results.title);
}

//---------------------------------------------------------
//  General operations associated with content
//---------------------------------------------------------
var frameRunning = false;
var lastFrameID = '';
function openiniframe(idName, url, title, preventHideEvent) {
    if (frameRunning && lastFrameID == idName)
        return false;
    var sHtml = '<iframe Id="' + idName + '" name="' + idName + '" width="100%" height="400" scrolling="no" marginwidth="0"  marginheight="0" frameborder="0" src="' + url + '"></iframe>';
    ShowContent(sHtml, title);
    //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 openindialog(idName, url, title, w, h) {
    var myBody = $('<div id="temp_dialog"></div>')
        .html('<iframe Id="' + idName + '" name="awqaf" width="100%" height="100%" scrolling="no" marginwidth="0"  marginheight="0" frameborder="0" src="' + url + '"></iframe>');
    showDialog(title, myBody, w ? w : 650, h ? w : 480, true, false, function() { dialog = this; }, function() { $(myBody).remove(); });
    return false;
}

function SetiFrameHeight(idName, mainElementID) {
    $('#' + idName).height($('#' + idName).contents().find('#' + mainElementID + '').height());
}

function expandcontent(cid) {
    $('#' + cid).toggleClass('switchcontentshow').toggleClass('switchcontent');
}

function OnContentError(result) {
    alert("Content Error: " + result);
    PlayMarque(true);
}

var contentAnimationID = 0;
function CloseContent() {
    $("#contentPlace").css({ display: "none", visibility: "hidden" });
    $("#contentSubBody").hide().html("empty");
    $("#contentMainBody").show(contentAnimationID == 0 ? "" : "slow");
    PlayMarque(true);
    DisplayBanners();
	frameRunning = false;
}


function ShowContent(sHtml, sTitle, allowTitle, animationID) {
	if(frameRunning)
	{
		var myBody = $(sHtml);
		showDialog(sTitle, myBody, 800, 600, true, false, null, function() { $(myBody).remove(); });
		return;
	}
    //contentPlace:
    //  It is the first container of all required elements used in showing and animating requested-content (sHTML)
    //  It exists in ContentPlace web-user-control, 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;
    }
    //return the parent of the given HTML to allow operation chaining
    return $("#contentSubBody");
}


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;
}

//---------------------------------------------------------
//  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()
    .find('#dataContainer')//adjust template class of container .. scrol or not
        .addClass(isPop ? 'popup' : 'inline')
    .end()
    .find('#dataContainer2')//adjust template class of inner container .. width is 92% or 100%
        .addClass(isPop ? 'popup2' : 'inline2')
    .end();
    if (isPop)
        showDialog(caption, myBody, 600, 500, false, true, null, function() { $(myBody).remove(); });
    return myBody;
}

