/// <reference path="jquery-1.3.2-vsdoc.js" />

$(document).ready(function() {

    // In case the event/news rotator was clicked
    $('#EventsDiv').hide(); // on load, news are shown only // Correction, this other div will never be shown anymore

    $('#divFooterEventsTab').click(function() {
        if (window.location.pathname.indexOf("/NewsNEvents") == -1) {
            location.href = '/NewsNEvents#filterType=Events&getAll=1';
        }
        else {
            $('#filterByEvents').attr('checked', true);
            $.bbq.removeState('newsNEventsId');
            $.bbq.pushState('filterType=' + "Events");
        }
    });
    /* it wont show anyways
    $('#EventsDiv').click(function() {
    if (window.location.pathname.indexOf("/NewsNEvents") == -1) {
    location.href = '/NewsNEvents/?p=Events#filterType=Events&getAll=1&newsNEventsId=' + $('#Eventval' + currentDisplayedEvent).val();
    }
    else {
    $.bbq.pushState('newsNEventsId=' + $('#Eventval' + currentDisplayedEvent).val());
    $.bbq.pushState('filterType=' + "Events");
    }
    });*/

    $('#divFooterNewsTab').click(function() {
        if (window.location.pathname.indexOf("/NewsNEvents") == -1) {
            location.href = '/NewsNEvents#filterType=News&getAll=1';
        }
        else {
            $('#filterByNews').attr('checked', true);
            $.bbq.removeState('newsNEventsId');
            $.bbq.pushState('filterType=' + "News");
        }
    });
    $('#NewsDiv').click(function() {
        if (window.location.pathname.indexOf("/NewsNEvents") == -1) {
            var filterType = ($('#Newsval' + currentDisplayedNews).attr('Iamanevent') != null) ? "Events" : "News";
            location.href = '/NewsNEvents/#filterType=' + filterType + '&getAll=1&newsNEventsId=' + $('#Newsval' + currentDisplayedNews).val();
        }
        else {
            $.bbq.pushState('newsNEventsId=' + $('#Newsval' + currentDisplayedNews).val());
            if ($('#Newsval' + currentDisplayedNews).attr('Iamanevent') != null) {
                $('#filterByEvents').attr('checked', true);
                $.bbq.pushState('filterType=' + "Events");
            }
            else {
                $('#filterByNews').attr('checked', true);
                $.bbq.pushState('filterType=' + "News");
            }
        }
    });


});

function getURLParameter(name) {
    return unescape(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
    );
}

function switchLanguage(div) {
    //if it is not selected, do something, otherwise NOTHING
    if (div.className.indexOf("selected") == -1) {
        if (div.id == "divLanguageSwitchEnglish") {
            document.getElementById("divLanguageSwitchArabic").className = "arabic adjustTop";
            document.getElementById("divLanguageSwitchEnglish").className = "english selected adjustTop";
           // document.getElementById("arabicCompanyProfile").style.display = 'none';
          //  document.getElementById("englishCompanyProfile").style.display = '';
            // document.getElementById("arCompanyLogo").style.display = 'none';
            //document.getElementById("companyLogo").style.display = '';

            if ($("#englishCompanyProfile").length > 0) {
                $("#englishCompanyProfile").css('display', '');
            }
            if ($("#arabicCompanyProfile").length > 0) {
                $("#arabicCompanyProfile").css('display', 'none');
            }

            if ($("#arCompanyLogo").length > 0) {
                $("#arCompanyLogo").css('display', 'none');
            }
            if ($("#companyLogo").length > 0) {
                $("#companyLogo").css('display', 'none');
            }
            
        }
        else {
            document.getElementById("divLanguageSwitchArabic").className = "arabic selected adjustTop";
            document.getElementById("divLanguageSwitchEnglish").className = "english adjustTop";
            //document.getElementById("arabicCompanyProfile").style.display = '';
           // document.getElementById("englishCompanyProfile").style.display = 'none';
            //document.getElementById("arCompanyLogo").style.display = '';
           // document.getElementById("companyLogo").style.display = 'none';

            if ($("#arabicCompanyProfile").length > 0) {
                $("#arabicCompanyProfile").css('display', '');
            }

            if ($("#englishCompanyProfile").length > 0) {
                $("#englishCompanyProfile").css('display', 'none');
            }

            if ($("#arCompanyLogo").length > 0) {
                $("#arCompanyLogo").css('display', 'none');
            }


            if ($("#companyLogo").length > 0) {
                $("#companyLogo").css('display', 'none');
            }
        }
    }
}

function switchVacancyLanguage(div) {
    //if it is not selected, do something, otherwise NOTHING
    if (!$(div).hasClass("selected")) {
        if (div.id == "divLanguageSwitchEnglish") {
            $("#divLanguageSwitchArabic").removeClass("selected");
            $("#divLanguageSwitchEnglish").addClass("selected");
        }
        else {
            $("#divLanguageSwitchArabic").addClass("selected");
            $("#divLanguageSwitchEnglish").removeClass("selected");
        }
        var visibleVacancies = $(".vacancy:visible");
        var invisibleVacancies = $(".vacancy:hidden");
        visibleVacancies.hide();
        invisibleVacancies.show();
    }
}

function displayMedia(mediaId, type) {
    if (currentlySelectedInterview != -1 && currentlySelectedInterview != mediaId) {
        $('#interviewAudio' + currentlySelectedInterview).hide();
        $('#interviewVideo' + currentlySelectedInterview).hide();
        $('#interviewIntroText' + currentlySelectedInterview).hide();
        $('#interviewDetailText' + currentlySelectedInterview).hide();

        $('#interview' + currentlySelectedInterview).removeClass('watch_now');
    }

    currentlySelectedInterview = mediaId;
    $('#interview' + currentlySelectedInterview).addClass('watch_now');
    
    if (type == 'audio')
        $('#interviewAudio' + currentlySelectedInterview).show();
    else
        $('#interviewAudio' + currentlySelectedInterview).hide();
    if (type == 'video')
        $('#interviewVideo' + currentlySelectedInterview).show();
    else
        $('#interviewVideo' + currentlySelectedInterview).hide();
    if (type == 'text') {
        $('#interviewIntroText' + currentlySelectedInterview).show();
        $('#interviewDetailText' + currentlySelectedInterview).show();
    }
    else {
        $('#interviewIntroText' + currentlySelectedInterview).hide();
        $('#interviewDetailText' + currentlySelectedInterview).hide();
    }
}

function AUloadMovie(URL, audioContainer) {
    if (window.document[audioContainer].SetVariable == undefined) {
        setTimeout('AUloadMovie(\'' + URL + '\', \'' + audioContainer + '\')', 100);
    }
    else {
        window.document[audioContainer].SetVariable("sound", URL);
    }
}

function getDetails(url, hdnId) {
    location.href = url + document.getElementById(hdnId).value;
}

function getDetailsViaAjax(url, hdnId) {
    makeGETRequest(url + document.getElementById(hdnId).value, 'gridListingDiv', '');
    selectedValue = $('#categoryId').val();
    $('#categoryIdDiv').html('');
    GWT_entryPoint();
}

function JQueryBBQNavigation(gid, cid) {
    $(window).hashchange(function() {
        var hash = $.deparam.fragment();
        var filterType = hash.filterType;
        var linkToBrands = (hash.linkToBrands != null) ? hash.linkToBrands.split(',') : "";
        var linkToCompanies = (hash.linkToCompanies != null) ? hash.linkToCompanies.split(',') : "";
        var albumId = hash.albumId;
        var photoId = hash.photoId;
        var videoId = hash.videoId;

        if (videoId != null && $('#videoslisting').length != 0) {
            loadVideo(videoId);
            return;
        }

        $('#gridListingDiv').html('');
        $('#gridListingDiv').addClass('loading2');

        ///////////////////////////////////////////////////////////
        ///////////////////////   Brands  /////////////////////////
        ///////////////////////////////////////////////////////////
        $('#divBrandsSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToBrands/, '');
            $(this).attr('checked', ($.inArray(id, linkToBrands) != -1));
        });
        var allBrandsChecked = true;
        $('#divBrandsSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToBrands/, '');
            if ($.inArray(id, linkToBrands) == -1) {
                allBrandsChecked = false;
                return false;
            }
        });
        $('#chkboxAllBrands').attr('checked', allBrandsChecked);
        ///////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////


        ///////////////////////////////////////////////////////////
        //////////////////////   Companies  ///////////////////////
        ///////////////////////////////////////////////////////////
        $('#divCompaniesSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToCompanies/, '');
            $(this).attr('checked', ($.inArray(id, linkToCompanies) != -1));
        });
        var allCompaniesChecked = true;
        $('#divCompaniesSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToCompanies/, '');
            if ($.inArray(id, linkToCompanies) == -1) {
                allCompaniesChecked = false;
                return false;
            }
        });
        $('#chkboxAllCompanies').attr('checked', allCompaniesChecked);
        ///////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////

        $('#chkboxLinkToGroup').attr('checked', ($.inArray(String(gid), linkToCompanies) != -1));
        $('#chkboxLinkToChairman').attr('checked', ($.inArray(String(cid), linkToCompanies) != -1));
        $('#albumId').val(albumId);

        //finally apply filter again =D
        if (albumId != null || photoId != null) {
            if (photoId != null) {
                // Is the album already loaded or was the URL copied so that I load the album before displaying the pic
                if ($('#albumLoaded').length == 0) {
                    makePOSTRequest('/MediaCenter/GetAlbum', "albumId=" + albumId, 'gridListingDiv', 'loadPhoto(\'' + photoId + '\');turnOffLoading();');
                }
                else {
                    loadPhoto(photoId);
                }
            }
            else {
                makePOSTRequest('/MediaCenter/GetAlbum', "albumId=" + albumId, 'gridListingDiv', 'turnOffLoading()');
            }
            //showPhotoById(\'' + photoId + '\')
        }
        else {
            var parameters = "filterType=" + filterType + "&linkToBrands=" + linkToBrands.join(',') + "&linkToCompanies=" + linkToCompanies.join(',');
            makePOSTRequest('/MediaCenter/ApplyFilter', parameters, 'gridListingDiv', 'turnOffLoading()');
        }
    });

    // Since the event is only triggered when the hash changes, we need to trigger
    // the event now, to handle the hash the page may have loaded with.
    $(window).hashchange();
}
function turnOffLoading() {
    $('#gridListingDiv').removeClass('loading2');
    
    ////////// RELATED TO VIDEO GALLERY
    if ($('#singleVideo').length != 0 && $("#JWPlayerContainer").length == 0)
        initializeVideo();
    if ($.bbq.getState('videoId') != null)
        loadVideo($.bbq.getState('videoId'));
    ////////// RELATED TO VIDEO GALLERY
}

function NewsNEventsBBQNavigation(gid, cid) {
    $(window).hashchange(function() {
        var hash = $.deparam.fragment();
        var filterType = hash.filterType;
        var linkToBrands = (hash.linkToBrands != null) ? hash.linkToBrands.split(',') : "";
        var linkToCompanies = (hash.linkToCompanies != null) ? hash.linkToCompanies.split(',') : "";
        //var month = hash.month;
        //var year = hash.year;
        var dateFrom = hash.dateFrom;
        var dateTo = hash.dateTo;
        var keywords = hash.keywords;
        var newsNEventsId = hash.newsNEventsId;

        if (hash.getAll != null) {
            initializeNewsNEventsFilter();
            return;
        }

        ///////////////////////////////////////////////////////////
        ///////////////////////   Brands  /////////////////////////
        ///////////////////////////////////////////////////////////
        $('#divBrandsSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToBrands/, '');
            $(this).attr('checked', ($.inArray(id, linkToBrands) != -1));
        });
        var allBrandsChecked = true;
        $('#divBrandsSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToBrands/, '');
            if ($.inArray(id, linkToBrands) == -1) {
                allBrandsChecked = false;
                return false;
            }
        });
        $('#chkboxAllBrands').attr('checked', allBrandsChecked);
        ///////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////


        ///////////////////////////////////////////////////////////
        //////////////////////   Companies  ///////////////////////
        ///////////////////////////////////////////////////////////
        $('#divCompaniesSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToCompanies/, '');
            $(this).attr('checked', ($.inArray(id, linkToCompanies) != -1));
        });
        var allCompaniesChecked = true;
        $('#divCompaniesSubMenu input:checkbox').each(function() {
            var id = $(this).attr('id').replace(/^chkboxLinkToCompanies/, '');
            if ($.inArray(id, linkToCompanies) == -1) {
                allCompaniesChecked = false;
                return false;
            }
        });
        $('#chkboxAllCompanies').attr('checked', allCompaniesChecked);
        ///////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////

        $('#chkboxLinkToGroup').attr('checked', ($.inArray(String(gid), linkToCompanies) != -1));
        $('#chkboxLinkToChairman').attr('checked', ($.inArray(String(cid), linkToCompanies) != -1));

        //finally apply filter again =D
        if (newsNEventsId != null) {
            makePOSTRequest('/NewsNEvent/GetNewsNEvent', "filterType=" + filterType + "&newsNEventsId=" + newsNEventsId, 'gridListingDiv', '');
        }
        else {
            var parameters = "filterType=" + filterType + "&linkToBrands=" + linkToBrands.join(',') + "&linkToCompanies=" + linkToCompanies.join(',');
            parameters += "&dateFrom=" + dateFrom + "&dateTo=" + dateTo + "&keywords=" + keywords;
            if ($.bbq.getState('page') != null)
                parameters += "&page=" + ($.bbq.getState('page'));
            if (getURLParameter('p') != "null")
                parameters += "&p=" + (getURLParameter('p'));
            makePOSTRequest('/NewsNEvent/ApplyFilter', parameters, 'gridListingDiv', '');
        }
    });

    // Since the event is only triggered when the hash changes, we need to trigger
    // the event now, to handle the hash the page may have loaded with.
    $(window).hashchange();
}

function mediaCenterChangeFilter(obj) {
    $('#filterByPhotoGallery').attr('checked', (obj.id == "filterByPhotoGallery"));
    $('#filterByVideos').attr('checked', (obj.id == "filterByVideos"));
    $('#filterByPressReleases').attr('checked', (obj.id == "filterByPressReleases"));
    $('#filterByDownloadableFiles').attr('checked', (obj.id == "filterByDownloadableFiles"));
    if (obj.id != "filterByPhotoGallery") {
        $.bbq.removeState('albumId');
        $.bbq.removeState('photoId');
    }
    if (obj.id != "filterByVideos") {
        $.bbq.removeState('videoId');
    }

    applyMediaCenterFilter();
}

function newsNEventsChangeFilter(obj) {
    $('#filterByNews').attr('checked', (obj.id == "filterByNews"));
    $('#filterByEvents').attr('checked', (obj.id == "filterByEvents"));

    applyNewsNEventsFilter();
}

function checkUncheckAllBrands(obj) {
    for (i = 0; i < listOfBrands.length; i++) {
        document.getElementById('chkboxLinkToBrands' + listOfBrands[i]).checked = obj.checked;
    }
    if ((obj.checked && !$('#divBrandsSubMenu').is(":visible")) || (!obj.checked && $('#divBrandsSubMenu').is(":visible")))
        mediaCenterToggleBrands();
    if (window.location.pathname.indexOf("/NewsNEvents") == -1)
        applyMediaCenterFilter();
    else
        applyNewsNEventsFilter();
}

function checkUncheckAllCompanies(obj) {
    for (i = 0; i < listOfCompanies.length; i++) {
        document.getElementById('chkboxLinkToCompanies' + listOfCompanies[i]).checked = obj.checked;
    }
    if ((obj.checked && !$('#divCompaniesSubMenu').is(":visible")) || (!obj.checked && $('#divCompaniesSubMenu').is(":visible")))
        mediaCenterToggleCompanies();
    if (window.location.pathname.indexOf("/NewsNEvents") == -1)
        applyMediaCenterFilter();
    else
        applyNewsNEventsFilter();
}

function mediaCenterToggleBrands() {
    $('#divBrandsSubMenu').slideToggle("fast", function() {
        if ($('#divBrandsSubMenu').is(":visible")) {
            $('#brandsToggler').removeClass("show_down");
            $('#brandsToggler').addClass("close_menu");
            $('#brandsToggler').attr('title', 'Close list');
        }
        else {
            $('#brandsToggler').removeClass("close_menu");
            $('#brandsToggler').addClass("show_down");
            $('#brandsToggler').attr('title', 'Expand list');
        }
    });
}

function mediaCenterToggleCompanies() {
    $('#divCompaniesSubMenu').slideToggle("fast", function() {
        if ($('#divCompaniesSubMenu').is(":visible")) {
            $('#companiesToggler').removeClass("show_down");
            $('#companiesToggler').addClass("close_menu");
            $('#companiesToggler').attr('title', 'Close list');
        }
        else {
            $('#companiesToggler').removeClass("close_menu");
            $('#companiesToggler').addClass("show_down");
            $('#companiesToggler').attr('title', 'Expand list');
        }
    });
}

function applyMediaCenterFilter() {
    var parameters = "";
    var filterType = "";
    var linkToBrands = "";
    var linkToCompanies = "";
    var albumId = "";

    if (document.getElementById('filterByPhotoGallery').checked)
        filterType = $('#filterByPhotoGallery').val();
    if (document.getElementById('filterByVideos').checked)
        filterType = $('#filterByVideos').val();
    if (document.getElementById('filterByPressReleases').checked)
        filterType = $('#filterByPressReleases').val();
    if (document.getElementById('filterByDownloadableFiles').checked)
        filterType = $('#filterByDownloadableFiles').val();


    for (i = 0; i < listOfBrands.length; i++) {
        linkToBrands += (document.getElementById('chkboxLinkToBrands' + listOfBrands[i]).checked) ? document.getElementById('hdnLinkToBrands' + listOfBrands[i]).value + "," : "";
    }
    if (linkToBrands.substr(linkToBrands.length - 1, 1) == ",")
        linkToBrands = linkToBrands.substr(0, linkToBrands.length - 1);

    for (i = 0; i < listOfCompanies.length; i++) {
        linkToCompanies += (document.getElementById('chkboxLinkToCompanies' + listOfCompanies[i]).checked) ? document.getElementById('hdnLinkToCompanies' + listOfCompanies[i]).value + "," : "";
    }
    if (linkToCompanies.substr(linkToCompanies.length - 1, 1) == ",")
        linkToCompanies = linkToCompanies.substr(0, linkToCompanies.length - 1);

    linkToCompanies += (document.getElementById('chkboxLinkToChairman').checked) ? ((linkToCompanies != "") ? "," : "") + document.getElementById('hdnLinkToChairman').value : "";
    linkToCompanies += (document.getElementById('chkboxLinkToGroup').checked) ? ((linkToCompanies != "") ? "," : "") + document.getElementById('hdnLinkToGroup').value : "";

    $.bbq.pushState('filterType=' + filterType);
    $.bbq.pushState('linkToBrands=' + linkToBrands);
    $.bbq.pushState('linkToCompanies=' + linkToCompanies);
    //$.bbq.removeState('albumId');
    //$.bbq.removeState('photoId');
}

function applyNewsNEventsFilter() {
    var parameters = "";
    var filterType = "";
    var linkToBrands = "";
    var linkToCompanies = "";
    var albumId = "";

    if (document.getElementById('filterByNews').checked)
        filterType = $('#filterByNews').val();
    if (document.getElementById('filterByEvents').checked)
        filterType = $('#filterByEvents').val();

    for (i = 0; i < listOfBrands.length; i++) {
        linkToBrands += (document.getElementById('chkboxLinkToBrands' + listOfBrands[i]).checked) ? document.getElementById('hdnLinkToBrands' + listOfBrands[i]).value + "," : "";
    }
    if (linkToBrands.substr(linkToBrands.length - 1, 1) == ",")
        linkToBrands = linkToBrands.substr(0, linkToBrands.length - 1);

    for (i = 0; i < listOfCompanies.length; i++) {
        linkToCompanies += (document.getElementById('chkboxLinkToCompanies' + listOfCompanies[i]).checked) ? document.getElementById('hdnLinkToCompanies' + listOfCompanies[i]).value + "," : "";
    }
    if (linkToCompanies.substr(linkToCompanies.length - 1, 1) == ",")
        linkToCompanies = linkToCompanies.substr(0, linkToCompanies.length - 1);
    
    linkToCompanies += (document.getElementById('chkboxLinkToChairman').checked) ? ((linkToCompanies != "") ? "," : "") + document.getElementById('hdnLinkToChairman').value : "";
    linkToCompanies += (document.getElementById('chkboxLinkToGroup').checked) ? ((linkToCompanies != "") ? "," : "") + document.getElementById('hdnLinkToGroup').value : "";

    $.bbq.pushState('filterType=' + filterType);
    $.bbq.pushState('linkToBrands=' + linkToBrands);
    $.bbq.pushState('linkToCompanies=' + linkToCompanies);
    // No more > $.bbq.pushState('month=' + ($.inArray($('#monthFilter').html().toLowerCase(), months) + 1));
    // No more > $.bbq.pushState('year=' + $('#yearFilter').html());

    $.bbq.pushState('dateFrom=' + $('#dateFrom').val());
    $.bbq.pushState('dateTo=' + $('#dateTo').val());
    $.bbq.pushState('keywords=' + ($('#keywords').val() == 'Keyword Search' ? '' : $('#keywords').val()));

    // Remove the page when user changes filter
    $.bbq.removeState('page');
    
    if ($.bbq.getState('backToCompany') != null) {
        $('.backToCompany').attr("href", $.bbq.getState('backToCompany'));
        $('.backToCompany').show();
    }
    
//    if ($.bbq.getState('backToBrand') != null) {
//        $('.backToBrand').attr("href", $.bbq.getState('backToBrand'));
//        $('.backToBrand').show();
//    }
}

function getMoreNewsEvents() {
    if ($.bbq.getState('page') != null)
        $.bbq.pushState('page=' + (parseInt($.bbq.getState('page')) + 1));
    else
        $.bbq.pushState('page=' + 1);        
}

function initializeMediaCenterFilter() {
    //if my fragment is empty, then I need to collect my default filter data
    var fragment = $.param.fragment();
    if ((fragment != "") && ($.bbq.getState('filterType') != null)) {
        // Take values from fragment and set the checkboxes
        var filterType = $.bbq.getState('filterType');

        document.getElementById('filterByPhotoGallery').checked = (filterType == $('#filterByPhotoGallery').val()) ? true : false;
        document.getElementById('filterByVideos').checked = (filterType == $('#filterByVideos').val()) ? true : false;
        document.getElementById('filterByPressReleases').checked = (filterType == $('#filterByPressReleases').val()) ? true : false;
        document.getElementById('filterByDownloadableFiles').checked = (filterType == $('#filterByDownloadableFiles').val()) ? true : false;

        var linkToBrands = ($.bbq.getState('linkToBrands') != null && $.bbq.getState('linkToBrands') != "") ? $.bbq.getState('linkToBrands').split(',') : "";
        for (i = 0; i < linkToBrands.length; i++) {
            $('#chkboxLinkToBrands' + linkToBrands[i]).attr('checked', true);
        }
        $('#chkboxAllBrands').attr('checked', ($('#divBrandsSubMenu :checkbox:not(:checked)').length == 0));
        
        // Expanding brands in case only some companies are checked
        if (($('#divBrandsSubMenu :checkbox:checked').length > 0) && ($('#divBrandsSubMenu :checkbox:checked').length < $('#divBrandsSubMenu :checkbox').length))
            mediaCenterToggleBrands();

        var linkToCompanies = ($.bbq.getState('linkToCompanies') != null && $.bbq.getState('linkToCompanies') != "") ? $.bbq.getState('linkToCompanies').split(',') : "";
        for (i = 0; i < linkToCompanies.length; i++) {
            $('#chkboxLinkToCompanies' + linkToCompanies[i]).attr('checked', true);
        }
        $('#chkboxAllCompanies').attr('checked', ($('#divCompaniesSubMenu :checkbox:not(:checked)').length == 0));

        // Expanding companies in case only some companies are checked
        if (($('#divCompaniesSubMenu :checkbox:checked').length > 0) && ($('#divCompaniesSubMenu :checkbox:checked').length < $('#divCompaniesSubMenu :checkbox').length))
            mediaCenterToggleCompanies();

        $('#chkboxLinkToChairman').attr('checked', ($.inArray($('#hdnLinkToChairman').val(), linkToCompanies) > -1));
        $('#chkboxLinkToGroup').attr('checked', ($.inArray($('#hdnLinkToGroup').val(), linkToCompanies) > -1));
    }
    else {
        // Check them all
        $('#chkboxAllBrands').attr('checked', true);
        $('#divBrandsSubMenu :checkbox').each(function() { $(this).attr('checked', true); });
        $('#chkboxAllCompanies').attr('checked', true);
        $('#divCompaniesSubMenu :checkbox').each(function() { $(this).attr('checked', true); });
        $('#chkboxLinkToChairman').attr('checked', true);
        $('#chkboxLinkToGroup').attr('checked', true);
        $.bbq.pushState('filterType=' + $('#filterByPhotoGallery').val());
    }
    applyMediaCenterFilter();
}

function initializeNewsNEventsFilter() {
    //if my fragment is empty, then I need to collect my default filter data
    var fragment = $.param.fragment();
    if ((fragment != "") && ($.bbq.getState('getAll') == null) && ($.bbq.getState('filterType') != null)) {
        // Take values from fragment and set the checkboxes
        var filterType = $.bbq.getState('filterType');

        if (getURLParameter('p') == "null") {
            document.getElementById('filterByNews').checked = (filterType == $('#filterByNews').val()) ? true : false;
            document.getElementById('filterByEvents').checked = (filterType == $('#filterByEvents').val()) ? true : false;
        }
        else {
            $('#filterByNews').attr('checked', filterType == $('#filterByNews').val());
            $('#filterByEvents').attr('checked', filterType == $('#filterByEvents').val());
        }

        var linkToBrands = ($.bbq.getState('linkToBrands') != null && $.bbq.getState('linkToBrands') != "") ? $.bbq.getState('linkToBrands').split(',') : "";
        for (i = 0; i < linkToBrands.length; i++) {
            $('#chkboxLinkToBrands' + linkToBrands[i]).attr('checked', true);
        }
        $('#chkboxAllBrands').attr('checked', ($('#divBrandsSubMenu :checkbox:not(:checked)').length == 0));

        // Expanding brands in case only some brands are checked
        if (($('#divBrandsSubMenu :checkbox:checked').length > 0) && ($('#divBrandsSubMenu :checkbox:checked').length < $('#divBrandsSubMenu :checkbox').length))
            mediaCenterToggleBrands();

        var linkToCompanies = ($.bbq.getState('linkToCompanies') != null && $.bbq.getState('linkToCompanies') != "") ? $.bbq.getState('linkToCompanies').split(',') : "";
        for (i = 0; i < linkToCompanies.length; i++) {
            $('#chkboxLinkToCompanies' + linkToCompanies[i]).attr('checked', true);
        }
        $('#chkboxAllCompanies').attr('checked', ($('#divCompaniesSubMenu :checkbox:not(:checked)').length == 0));

        // Expanding companies in case only some companies are checked
        if (($('#divCompaniesSubMenu :checkbox:checked').length > 0) && ($('#divCompaniesSubMenu :checkbox:checked').length < $('#divCompaniesSubMenu :checkbox').length))
            mediaCenterToggleCompanies();

        $('#chkboxLinkToChairman').attr('checked', ($.inArray($('#hdnLinkToChairman').val(), linkToCompanies) > -1));
        $('#chkboxLinkToGroup').attr('checked', ($.inArray($('#hdnLinkToGroup').val(), linkToCompanies) > -1));
    }
    else {
        // Check them all
        $('#chkboxAllBrands').attr('checked', true);
        $('#divBrandsSubMenu :checkbox').each(function() { $(this).attr('checked', true); });
        $('#chkboxAllCompanies').attr('checked', true);
        $('#divCompaniesSubMenu :checkbox').each(function() { $(this).attr('checked', true); });
        $('#chkboxLinkToChairman').attr('checked', true);
        $('#chkboxLinkToGroup').attr('checked', true);
        //if ($.bbq.getState('getAll') == null)
        //    $.bbq.pushState('filterType=' + $('#filterByNews').val());
        $('#filterByNews').attr('checked', $.bbq.getState('filterType') == $('#filterByNews').val());
        $('#filterByEvents').attr('checked', $.bbq.getState('filterType') == $('#filterByEvents').val());
        $.bbq.removeState('getAll');
    }
    applyNewsNEventsFilter();
}

var months = new Array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
function getMonth(direction) {
    var i = $.inArray($('#monthFilter').html().toLowerCase(), months);
    if (((i == 0) && (direction == -1)) || ((i == 11) && (direction == 1)))
        return;
    $('#monthFilter').html(months[i + direction].toUpperCase());
    $.bbq.pushState('month=' + ($.inArray($('#monthFilter').html().toLowerCase(), months) + 1));
}

function getYear(direction) {
    $('#yearFilter').html(parseInt($('#yearFilter').html()) + direction);
    $.bbq.pushState('year=' + $('#yearFilter').html());
}

function getNews(newsId) {
    $.bbq.pushState('newsNEventsId=' + newsId);
}

function GetAlbum(albumId) {
    $.bbq.pushState("albumId=" + albumId);
}

function getVideo(videoId) {
    $.bbq.pushState("videoId=" + videoId);
}

function displayAlbumPic(obj) {
    var currentDisplayedPic = document.getElementById('selectedImageThumb');
    document.getElementById(currentDisplayedPic.value).className = "album_content";
    currentDisplayedPic.value = obj.id;
    document.getElementById(currentDisplayedPic.value).className = "album_content selected";
    document.getElementById('divImage').style.backgroundImage = 'url(' + obj.childNodes[0].src + ')';
}

function loadPhoto(photoId) {
    var imgIndex = $("input[value='" + photoId + "']").attr('id').replace(/^photoId/,'');
    var imgUrl = '/Utils/getImage?location=' + $('#picUrl' + imgIndex).val() + '&width=551&height=100000';
    var imgCaption = $('#photoCaption' + imgIndex).val();
    var img = new Image();
    $('#divAlbum').empty().addClass('loading');

    //if ($('#photolisting').is(":visible")) {
    if (document.getElementById('photolisting').style.display == "none") {
        $('#photolisting').slideToggle('slow', function() { $('#singlePhoto').slideToggle('slow'); });
    }
    else {
        $('#singlePhoto').slideToggle('slow');
    }
    setupPhotoAlbumNavigationButtons(imgIndex);

    $(img).load(function() {
        $(this).hide();
        $('#divAlbum').removeClass('loading');
        $('#divAlbum').empty();
        $('#divAlbum').append(this);
        $('#divAlbum').append(imgCaption);
        $(this).fadeIn();
    })
    .error(function() {
        $('#divAlbum').html('The image failed to load');
        $('#divAlbum').removeClass('loading');
    })
    .attr('src', imgUrl);
}

function loadVideo(videoId) {
    $('#divVideo').empty().addClass('loading');

    $('#videoslisting').slideToggle('slow', function() {
        $('#singleVideo').slideToggle('slow', function() {
            if (document.getElementById('videoslisting').style.display == "none") {
                var videoToPlay = ($('#videoSrc' + videoId).val() != "") ? $('#videoSrc' + videoId).val() : $('#youtubeLink' + videoId).val();
                setTimeout("JWloadMovie('" + videoToPlay + "', 'JWPlayerContainer1', 'true')", 100);
            }
        });
    });
}

function setupPhotoAlbumNavigationButtons(index) {
    currentIndex = parseInt(index);
    if (currentIndex > 0) {
        $('#photolisting').hide();
        $('#previousPic').addClass('selected');
        $('#previousPic').unbind('click');
        $('#previousPic').click(function() {
        $('#photolisting').hide();
            $.bbq.pushState('photoId=' + $('#photoId' + (currentIndex - 1)).val());
        });
    }
    if (currentIndex < $('#nbOfThumbnails').val()) {
        $('#nextPic').addClass('selected');
        $('#nextPic').unbind('click');
        $('#nextPic').click(function() {
        $('#photolisting').hide();
            $.bbq.pushState('photoId=' + $('#photoId' + (currentIndex + 1)).val());
        });
    }
    if (currentIndex == $('#nbOfThumbnails').val()) {
        $('#nextPic').removeClass('selected');
        $('#nextPic').unbind('click');
    }
    if (currentIndex == 1) {
        $('#previousPic').removeClass('selected');
        $('#previousPic').unbind('click');
    }
}
/* ***************************************************************** */
var currentFooterTextIs = "news";
var currentDisplayedNews = 1;
var currentDisplayedEvent = 1;

function rotateNews() {
    $('#EventsDiv').hide();
    $('#NewsDiv').toggle("slow", function() {
        $('#NewsDiv').html($('#News' + currentDisplayedNews).val());
    });
    $('#NewsDiv').toggle("slow");
    currentDisplayedNews = (currentDisplayedNews == $('#nbOfNews').val()) ? 1 : (currentDisplayedNews + 1);
    // If there is only one record, stop the rotator
    if ($('#nbOfNews').val() == 1)
        clearInterval(newsRotatorTimer);
}

function rotateEvents() {
    $('#NewsDiv').hide();
    $('#EventsDiv').toggle("slow", function() {
        $('#EventsDiv').html($('#Events' + currentDisplayedEvent).val());
    });
     $('#EventsDiv').toggle("slow");
     currentDisplayedEvent = (currentDisplayedEvent == $('#nbOfEvents').val()) ? 1 : (currentDisplayedEvent + 1);
    // If there is only one record, stop the rotator
     if ($('#nbOfEvents').val() == 1)
         clearInterval(eventsRotatorTimer);
}

function flipToNews() {
    $('#divFooterNewsTab').addClass('selected');
    $('#divFooterEventsTab').removeClass('selected');

    clearInterval(eventsRotatorTimer);
    $('#NewsDiv').show();
    $('#EventsDiv').hide();
    if (currentFooterTextIs != "news") {
        newsRotatorTimer = setInterval(rotateNews, 5000);
        currentFooterTextIs = "news";
    }
}

function flipToEvents() {
    $('#divFooterNewsTab').removeClass('selected');
    $('#divFooterEventsTab').addClass('selected');

    clearInterval(newsRotatorTimer);
    $('#NewsDiv').hide();
    $('#EventsDiv').show();
    if (currentFooterTextIs != "events") {
        eventsRotatorTimer = setInterval(rotateEvents, 5000);
        currentFooterTextIs = "events";
    }
}
/* ***************************************************************** */

function submitContactUsForm() {
    if (($('#email').val().indexOf(".") == -1) || ($('#email').val().indexOf("@") == -1)) {
        $('#email').parent().addClass("missing");
        if ($('.required-alert').is(":hidden")) {
            $('.required-alert').slideToggle("slow");
        }
        return;
    }
    else {
        $('#email').parent().removeClass("missing");
        if ($('.required-alert').is(":visible")) { $('.required-alert').slideToggle("slow"); }
    }
    $('#formSubmit').hide();
    $('#formSubmitProcessing').show();
    makePOSTRequest('/Website/ContactUs', "name=" + $('#name').val() + "&email=" + $('#email').val() + "&message=" + $('#message').val(), 'formSubmitResult', 'submitContactUsFormCallback()');
}

function submitContactUsFormCallback() {
    if ($('#formSubmitResult').html() == "success") {
        document.getElementById('contactUsForm').reset()
        $('#formSubmit').show();
        $('#formSubmitProcessing').hide();
        alert('Message sent successfully!');
    }
    else {
        alert('An error occured, please try again!');
    }
}

function sitemapToggle(objId) {
    $('#' + objId).siblings('div').slideToggle("fast", function() {
        if ($('#' + objId).parent().hasClass("maximize")) {
            $('#' + objId).parent().removeClass("maximize");
            $('#' + objId).parent().addClass("minimize");
        }
        else {
            $('#' + objId).parent().addClass("maximize");
            $('#' + objId).parent().removeClass("minimize");
        }
    });
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

function validateApplicationForm() {
    var clearToSubmit = true;
    
    if ($('#txtName').val() == "") {
        clearToSubmit = false;
        $('#txtName').addClass('missing');
    }
    else {
        $('#txtName').removeClass('missing');
    }
    
    if ($('#txtNationality').val() == "") {
        clearToSubmit = false;
        $('#txtNationality').addClass('missing');
    }
    else {
        $('#txtNationality').removeClass('missing');
    }
    
    if ($('#txtDob').val() == "") {
        clearToSubmit = false;
        $('#txtDob').addClass('missing');
    }
    else {
        $('#txtDob').removeClass('missing');
    }
    
    if ($('#txtAddress').val() == "") {
        clearToSubmit = false;
        $('#txtAddress').addClass('missing');
    }
    else {
        $('#txtAddress').removeClass('missing');
    }

    if (!isValidEmailAddress($('#txtEmail').val())) {
        clearToSubmit = false;
        $('#txtEmail').addClass('missing');
    }
    else {
        $('#txtEmail').removeClass('missing');
    }

    if ($('#cv').val() == "") {
        clearToSubmit = false;
        $('#cv').parent().addClass('missing');
    }
    else {
        $('#cv').parent().removeClass('missing');
    }

    if (clearToSubmit) {
        $('#frmVacancyApplication').children().hide();
        $('.vacancyApplicationFooter').hide();
        $('#frmVacancyApplication').addClass('vacancyApplicationLoading');
        //$('#frmVacancyApplication').submit();
        $.post($('#frmVacancyApplication').attr('action'), { vacancyId: $('#vacancyId').val(), name: $('#txtName').val(), nationality: $('#txtNationality').val(), dob: $('#txtDob').val(), address: $('#txtAddress').val(), city: $('#txtCity').val(), street: $('#txtStreet').val(), phone: $('#txtPhone').val(), fax: $('#txtFax').val(), email: $('#txtEmail').val(), cv: $('#cv').val() },
                function(data) {
                    $('#frmVacancyApplication').removeClass('vacancyApplicationLoading');
                    if (data == "success") {
                        alert("Your form was successfully submitted");
                        document.getElementById('frmVacancyApplication').reset();
                        $('#frmVacancyApplication').children().show();
                        $('.vacancyApplicationFooter').show();
                    }
                    else {
                        alert("Something went wrong during form submission. Please try again.");
                        $('#frmVacancyApplication').children();
                        $('.vacancyApplicationFooter').show();
                    }
                });
    }
    else
        alert('Kindly, fill the required form fields correctly');
}

///////////////////////////////////////////////////////////////////////
///////////////////////      AJAX                  ////////////////////
///////////////////////////////////////////////////////////////////////

var xmlhttp;
function makeGETRequest(url, responseContainerId, callbackFunction) {

    xmlhttp = null;
    if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {// 4 = "loaded"
                if (xmlhttp.status == 200) {// 200 = "OK"
                    if (responseContainerId != null)
                        document.getElementById(responseContainerId).innerHTML = (xmlhttp.responseText);
                    if (callbackFunction != null && (typeof (callbackFunction) != undefined))
                        eval(callbackFunction);
                }
                else {
                    alert(xmlhttp.responseText)
                    alert("Problem retrieving data:" + xmlhttp.statusText);
                }
            }
        };
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
    else {
        alert("Your browser does not support XMLHTTP.");
    }
}
function makePOSTRequest(url, parameters, responseContainerId, callbackFunction) {
    xmlhttp = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        xmlhttp = new XMLHttpRequest();
        if (xmlhttp.overrideMimeType) {
            // set type accordingly to anticipated content type
            //xmlhttp.overrideMimeType('text/xml');
            xmlhttp.overrideMimeType('text/html');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!xmlhttp) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {// 4 = "loaded"
            if (xmlhttp.status == 200) {// 200 = "OK"
                if (responseContainerId != null)
                    document.getElementById(responseContainerId).innerHTML = (xmlhttp.responseText);
                if (callbackFunction != null && (typeof (callbackFunction) != undefined))
                    eval(callbackFunction);
            }
            else {
                //alert(xmlhttp.responseText)
                //alert("Problem retrieving data:" + xmlhttp.statusText);
            }
        }
    };
    xmlhttp.open('POST', url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", parameters.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(parameters);
}
///////////////////////////////////////////////////////////////////////
///////////////////////      AJAX                  ////////////////////
///////////////////////////////////////////////////////////////////////


function showOrganizStruct() {
    loadPopup();
    centerPopup();
}
