﻿//--------------------------------------------------------|    START: Header    |------------------------------------------------------//
//
//  This is the Code Global Module.
//
//  Dependencies:
//      1) Common.JS - this module contains common functionality used throughout the Groups websites.
//
//--------------------------------------------------------|    FINISH: Header    |------------------------------------------------------//


//Check for the COMMON Module
(typeof SAOSS_Host == 'undefined' || SAOSS_Host == '') ? alert("The COMMON module is missing. The support team has been notified of this issue (" + Math.floor(Math.random() * 563256 + 1) + ").") : '';

//Things to do immediately to hide things from user, but expose to search engines. THIS CODE WILL BE ENCRYPTED
    (getElement('TagCloud')) ? getElement('TagCloud').style.display = "none" : '';
    (getElement('ProfileKeywords')) ? getElement('ProfileKeywords').style.display = "none" : '';


var mainComplete = false;   //Used to track whether the SetupMain Method has been completed;

var SAOSS_Module = 'Global Module';
var SAOSS_Method = 'None';

var SAOSS_BannerServer = SAOSS_Host + '.sharedstore.org/images/';

//Website Switiches
SAOSS_UseErrorHandling = true;  //Change to FALSE to use native Error Handling


var BS;
var H = document.getElementsByTagName('head').item(0);

BS = document.createElement('BGSOUND');
BS.id = "118499_BGS"
BS.src = '/Midi/Silence.wav';
H.appendChild(BS)

var JingleImg;

var NewLine = '<br />';

goHome = function() {
    location = "/Home";
}

function playSound(Choice) {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'playSound';

    BS = getElement('118499_BGS');

    if ((BS.src != '/Midi/Silence.wav') && (BS.src != '')){  //The we're already plaing something.
        DoClearSound(); 
        return 
    };
    
    var Domain = ''
    var Sound = 'http://' + SAOSS_Host + '.118499.Org/Midi/';
    var SharedDomain = 'http://' + SAOSS_Host + '.118499.Org/Midi/';
    var Files = new Array();
    Files[0] = "Silence";
    Files[1] = "118499A";
    Files[2] = "118499B";
    Files[3] = "118499C";
    Files[4] = "118499D";
    Files[5] = "118499E";
    Files[6] = "118499F";
    Files[7] = "118499G";
    Files[8] = "118499H";
    Files[9] = "118499I";

    if (Choice == null) { Choice = 8 };
    
    if(BS == null) return;
	
//        switch (Choice)
//        {
//            case 0: {Sound += 'Silence'; break;}
//            case 1: {Sound += '118499A'; break;}
//            case 2: {Sound += '118499B'; break;}
//            
//            case 3: {Sound += '118499C'; break;}
//            case 4: {Sound += '118499D'; break;}
//            case 5: {Sound += '118499E'; break;}
//            case 6: {Sound += '118499F'; break;}
//            case 7: {Sound += '118499G'; break;}
//            case 8: {Sound += '118499H'; break;}
//            case 9: {Sound += '118499I'; break;}
//        }

    JingleImg = getElement('JingleImg')
    if (JingleImg) { JingleImg.src = '/Images/JingleOff.png'; }
      
       BS.src = SharedDomain + Files[Choice] + '.mp3';
       window.status = "Playing " + Files[Choice];
       setTimeout(DoClearSound, 11000);
}   //END: PlaySound

function DoEnter() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'doEnter';


}   //END: DoEnter
function DoRight() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'doRight';


}   //END: DoRight

function stopSound() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'stopSound';
    BS.src = '';
    if (JingleImg) { getElement('JingleImg').src = '/Images/Jingle.png'; }
}

function DoClearSound() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'DoClearSound';
    var Path = '/Midi/Silence.wav';
    stopSound(); 
    ClearSoundInterval = 10000;
    ClearSoundInterval = clearTimeout(ClearSoundInterval);
}


function SetUpMain() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'SetUpMain';

    if (window.location == 'http://' + SAOSS_Host + '.118499.org/Home/') {  //Play the Welcome Audio
        playSound(8);
    };

    if (window.screen.width > 1024 && window.screen.height > 768) {
        //var r = getElement('SearchBox')
        //r.style.backgroundImage = "url('/Images/SearchBox.png')";
    }
    
    fixPNGs(); 
    
    //Check for the Postcode Cookie - if unavailable, ask for the Postcode
    //doPostcode('Postcode',100,100);

    //Check for objects using common functions.
    (typeof doCheckHighslide == 'function') ? doCheckHighslide() : '';      //Check for Highslide Elements
    (typeof checkDialogs == 'function') ? checkDialogs() : '';              //Check for Dialogs and load JQuery and Thickbox
    (typeof doCheckVoteTags == 'function') ? doCheckVoteTags() : '';        //Check for Voting Tags

    doSponsors();
    

    
    (getElement('Charities')) ? SAOSS_LM('CharityFooter', 'CharityFooter', false) : alert('No ClarityLogos');

    (getElements('rating_cont')) ? SAOSS_LM('star_rating', 'star_rating', true) : alert('No Star Rating');


    //This copies the content from the FOOTER MENU to the SNAV
    //(getElement('MP_MainFooter_FootMenu') && getElement('SNAV')) ? getElement('SNAV').innerHTML = ('<div id="SNAVTOP"></div>' + getElement('MP_MainFooter_FootMenu').innerHTML + '<div id="SNAVBTM"></div>') : '';
    
    if (typeof SetupSecurity == 'function') { SetupSecurity(); };   //If the "SecuritySetup" method is available, then execute it.
    
    mainComplete = true;
    return mainComplete;
}



//----------------------------------------------------|    START: CSS Management    |---------------------------------------------------------------//





if (typeof document.createStyleSheet === 'undefined') {
    document.createStyleSheet = (function() {
        function createStyleSheet(href) {
            if (typeof href !== 'undefined') {
                var element = document.createElement('link');
                element.type = 'text/css';
                element.rel = 'stylesheet';
                element.href = href;
            }
            else {
                var element = document.createElement('style');
                element.type = 'text/css';
            }

            document.getElementsByTagName('head')[0].appendChild(element);
            var sheet = document.styleSheets[document.styleSheets.length - 1];

            if (typeof sheet.addRule === 'undefined')
                sheet.addRule = addRule;

            if (typeof sheet.removeRule === 'undefined')
                sheet.removeRule = sheet.deleteRule;

            return sheet;
        }

        function addRule(selectorText, cssText, index) {
            if (typeof index === 'undefined')
                index = this.cssRules.length;

            this.insertRule(selectorText + ' {' + cssText + '}', index);
        }

        return createStyleSheet;
    })();
}

//----------------------------------------------------|    FINISH: CSS Management    |---------------------------------------------------------------//


//----------------------------------------------------|    START: Image Functions    |---------------------------------------------------------------//

// correctly handle PNG transparency in Win IE 5.5 & 6.

var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);

function fixPNGs() { //This only needs doing in <= IE 6
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'fixPNGs';
    
    var PNGs = getElements('img')

    if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
        for (i = 0; i < PNGs.length; i++) {

            if (Right(PNGs[i].src, 3) == 'png') { fixPNG(PNGs[i].id); }
        }
    }
}

function fixPNG(myImage) {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'fixPNG';
    
    try {

        if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
            var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
            var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
            var imgTitle = (myImage.title) ?
		                 "title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
            var imgStyle = "display:inline-block;" + myImage.style.cssText
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
                      + " style=\"" + "width:" + myImage.width
                      + "px; height:" + myImage.height
                      + "px;" + imgStyle + ";"
                      + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                      + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
            myImage.outerHTML = strNewHTML
        }
    }
    catch (E) {
    }
}

function fixPNG2() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'fixPNG2';
    
    for (i = 0; i < document.images.length; i++) {
        var img = document.images[i]
        var imgName = img.src.toUpperCase()
        if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = (img.style.cssText) ? img.style.cssText + ";" : ""
            var floatOrBlock = "display:inline-block;"
            var oAttribs = img.attributes;
            for (var j = 0; j < oAttribs.length; j++) {
                var oAttrib = oAttribs[j];
                if (oAttrib.nodeName == "align") {
                    switch (oAttrib.nodeValue) {
                        case "left": floatOrBlock = "float:left;"; break;
                        case "right": floatOrBlock = "float:right;"; break;
                    }
                    break;
                }
            }
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            strNewHTML += " style=\"" + floatOrBlock + imgStyle
            strNewHTML += " width:" + img.width + "px; height:" + img.height + "px; "
            strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + img.src + "\');\">"
            strNewHTML += "</span>";
            img.outerHTML = strNewHTML
            i = i - 1
        }
    }
}

//----------------------------------------------------|    FINISH: Image Functions    |---------------------------------------------------------------//



function toggle(ImgID, DivID) {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'Toggle';
    
    var div = getElement(DivID);
    var GetImg = getElement(ImgID);
    var aDivs = getElements("div");
    var aImgs = getElements("img");

    //Apply ArrowExpand to all Arrow Images
    for (j = 0; j < aImgs.length; j++) {
        if (aImgs[j].id.substr(0, 2) == "CQ" && (aImgs[j].id.substr(0, 2) != "C_")) {
            aImgs[j].src = "/Images/ArrowExpand.gif";
        };
    };

    if (div.style.display == "none" || (div.style.display == "")) {
        for (i = 0; i < aDivs.length; i++) {
            if (aDivs[i].id.substr(0, 2) == "QA" || aDivs[i].id.substr(0, 2) == "ST") {
                aDivs[i].style.display = "none";
            };
        };
        div.style.display = "block";
        GetImg.src = "/Images/ArrowCollapse.gif";
    }
    else {
        div.style.display = "none";
        GetImg.src = "/Images/ArrowExpand.gif";
    };
};







//var myHead = document.getElementsByTagName('Head')



//if (myHead != 'undefined'){
  //  var NC = new 
  //  myHead.item(1).appendChild(NC);
//http://www.btexchanges.com/plumber/somerset/Search-Type/View-List/Page-1/Sort-Distance/Radius-15/Default.aspx
//}






//----------------------------------------------------|    START: Postcode Bubble   |-------------------------------------------------------------//


function doPostcode() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'doPostcode';
    
    var Body = getElement('MP_Body')
    //alert(Client.windowHeight()/2);
    var boxWidth = 437;
    var boxHeight = 253;

    createDiv('PostcodeBox', (Client.windowHeight() / 2) - (boxHeight / 2), (Client.windowWidth() / 2) -(boxWidth /2), boxHeight, boxWidth);
    var PC = getElement('PostcodeBox');
    PC.style.backgroundImage = 'url(/Images/PostcodeBubble.png)';
     
}






function Initialise() {



}  

//----------------------------------------------------|    FINISH: Postcode Bubble   |-------------------------------------------------------------//



//Global LoadModule(LM) Code - This is used to programically load JS Modules into the Client

if (typeof SAOSS_LM == 'function') {
    //SAOSS_LM('fade', 'select/fade');
    //SAOSS_LM('select', 'select/select');
    //SAOSS_LM('writeSelect', 'select/writeSelect');
}



function doYes(IMG) {

}
function doNo(IMG) {
    
}


//----------------------------------------------------|    START: Sponsors Control   |---------------------------------------------------------//

// This routine dertects the 'Sponsors Control' and loads advertisements from local businesses using the Postcode Cookie 

function doSponsors() {
    SAOSS_Module = 'Global Module'; SAOSS_Method = 'doSponsors';
    
    //  Get the Postcode Cookie;
    //  Get the Supporters DIV;
    //  Post request to MediaServer using Postcode;
    //  Load adverts into Sponsors Control;
    //  Roll open Sponsors Control and Load Sponsors.

    
    
    LoadSponsors();
    setInterval(LoadSponsors, 5000); 

}
function LoadSponsors() {

    var myArray = [null,null,null,null];
    var Count = 0;

    for (i = 0; Count <= myArray.length-1; i++) {
        
        var x = Math.floor(Math.random() * 21);

        if (myArray.find(x) == false) { //Then the number is unique;
            myArray[Count] = x;             //Assign the number to the element;
            Count += 1;                 //Increment the unique number count;
        }
    }

    myArray.shuffle();
    
    PageAd = getElement('InPageAd');
    (PageAd) ? PageAd.style.backgroundImage = 'url(' + SAOSS_BannerServer + myArray[0] + '.png' + ')' : '';

    Sponsors = getElement('Supporters');
    //(Sponsors) ? Sponsors.innerHTML = '<div id="SID01" style="background-image:url(' + SAOSS_BannerServer + myArray[1] + '.png' + ')"><p>' + SAOSS_BannerServer + myArray[1] + '"</p></div><div id="SID02" style="background-image:url(' + SAOSS_BannerServer + myArray[2] + '.png' + ')"><p>' + myArray[2] + '</p></div><div id="SID03" style="background-image:url(' + SAOSS_BannerServer + myArray[3] + '.png' + ')"><p>' + myArray[3] + '</p></div>' : '';
    var innerHTML = '';
    if (Sponsors){
        innerHTML += '<div id="SID01"><a rel="modalbox" href="' + SAOSS_BannerServer + '/Adverts/' + myArray[1] + '.png"><img src="' + SAOSS_BannerServer + '/Banners/' + myArray[1] + '.png"/ title="Click to View"></a></div>';
        innerHTML += '<div id="SID02"><a rel="modalbox" href="' + SAOSS_BannerServer + '/Adverts/' + myArray[2] + '.png"><img src="' + SAOSS_BannerServer + '/Banners/' + myArray[2] + '.png"/ title="Click to View"></a></div>';
        innerHTML += '<div id="SID03"><a rel="modalbox" href="' + SAOSS_BannerServer + '/Adverts/' + myArray[3] + '.png"><img src="' + SAOSS_BannerServer + '/Banners/' + myArray[3] + '.png"/ title="Click to View"></a></div>';

        Sponsors.innerHTML = innerHTML;
        
        //PrepareOverlay();
    }
    
}

Array.prototype.find = function(searchStr) {  var returnArray = false;  for (i=0; i<this.length; i++) {    if (typeof(searchStr) == 'function') {      if (searchStr.test(this[i])) {        if (!returnArray) { returnArray = [] }        returnArray.push(i);      }    } else {      if (this[i]===searchStr) {        if (!returnArray) { returnArray = [] }        returnArray.push(i);      }    }  }  return returnArray;}
Array.prototype.shuffle = function (){         for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--i], this[i]=this[rnd], this[rnd]=tmp);};

//----------------------------------------------------|    FINISH: Sponsors Control   |---------------------------------------------------------//

function PrepareOverlay() {

//This code was adapted from: http://webcloud.se/article/Building_modal_panels_with_jQuery

    (function($) {
        $.fn.extend({
            modalPanel: function() {
            
                //Our function for hiding the modalbox
                function modalHide() {
                    $(document).unbind("keydown", handleEscape);
                    var remove = function() { $(this).remove(); };
                    overlay.fadeOut(remove);
                    modalWindow
					.fadeOut(remove)
					.empty();
                }

                //Our function that listens for escape key.
                function handleEscape(e) {
                    if (e.keyCode == 27) {
                        modalHide();
                    }
                }

                //Create our overlay object
                var overlay = $("<div id='modal-overlay'></div>");
                //Create our modal window
                var modalWindow = $("<div id='modal-window'></div>");

                return this.each(function() {
                    //Listen for clicks on objects passed to the plugin
                    $(this).click(function(e) {

                        if (typeof document.body.style.maxHeight === "undefined") { //if IE 6
                            $("body", "html").css({ height: "100%", width: "100%" });
                        }

                        //Append the overlay to the document body
                        $("body").append(overlay.click(function() { modalHide(); }));
                        //Add a loader to our page
                        $("body").append("<div id='modal-load'></div>");

                        //Set the css and fade in our overlay
                        overlay.css("opacity", 0.8);
                        overlay.show();

                        //Prevent the anchor link from loading
                        e.preventDefault();

                        //Activate a listener 
                        $(document).keydown(handleEscape);

                        //Load the image
                        var img = new Image();
                        $(img).load(function() {
                            var imageWidth = img.width / 2;
                            var imageHeight = img.height / 2;
                            modalWindow.css({
                                "margin-left": -imageWidth
                            });

                            if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
                                modalWindow.css({
                                    "margin-top": -imageHeight
                                });
                            }

                            $("#modal-load").remove();
                            modalWindow.append(img);
                            $(this).addClass("modal-image");
                            $("body").append(modalWindow);
                            modalWindow.fadeIn(50);
                        })
					.attr({ src: this.href }).click(function() {
					    modalHide();
					});
                    });
                });
            }
        });
    })(jQuery);

    (function($) {
        $.fn.extend({
            overlay: function() {
                
                //Create our overlay object
                var overlay = $("<div id='modal-overlay'></div>");

                return this.each(function() {

                    //Listen for clicks on objects passed to the plugin
                    $(this).click(function(e) {

                        //Append the overlay to the document body
                        $("body").append(overlay.click(function() { modalHide(); }))

                        //Set the css and fade in our overlay
                        overlay.css("opacity", 0.8);
                        overlay.fadeIn(150);

                        //Prevent the anchor link from loading
                        e.preventDefault();

                        //Activate a listener 
                        $(document).keydown(handleEscape);
                    });
                });

                //Our function for hiding the modalbox
                function modalHide() {

                    $(document).unbind("keydown", handleEscape)
                    var remove = function() {

                        $(this).remove();
                    }
                    overlay.fadeOut(remove);
                }

                //Our function that listens for escape key.
                function handleEscape(e) {

                    if (e.keyCode == 27) {

                        modalHide();
                    }
                }
            }
        });
    })(jQuery);

    $(function() {
        //$('a[rel*=overlay]').overlay();
        $('a[rel*=modalbox]').modalPanel();
    });

}

//$("img").click(function(event) {
//    event.preventDefault();
//    $(this).hide("slow");
//});




//----------------------------------------------------|    START: Charity Scroller   |---------------------------------------------------------//

function doCharityScroller() {

    getElement('Ads').innerHTML = '<div id="CharityScroller">' + getElement('Charities').innerHTML + '</div>';

}


//----------------------------------------------------|    FINISH: Charity Scroller   |---------------------------------------------------------//



window.onkeyup = WhichKeyPress;



//--------------------------------------------------------|    END: Module    |-----------------------------------------------------------------//

(typeof addLoadEvent == 'function') ? addLoadEvent(SetUpMain) : '';  //Replace FUNCTION with any function required to be called upon Page Load

(typeof SAOSS_AddModule != 'undefined') ? SAOSS_AddModule('Global Module', '1.0', false) : '';   //Add this Module to the Modules Array (Tracking)


