﻿var jsReady = false;
var flashReady = false;  
var disableLinks = false; 

var contentAppear;
var contentFade;
var stafDisplay = false;
var shareDisplay = false;

var safariSplit = "%23"

// List of browsers for the show/hide functionality (rather than the fade/appear)
// When running, we check against the 'browser' variable set in global.js
var browserArray = new Array();
    browserArray[0] = "ie6"
    browserArray[1] = "ie7"
    browserArray[2] = "ie8"


function gotFlash(){
    if (hasFlashVersion(9)){
        return ("&amp;hf=1")
    }else{
        return ("&amp;hf=0")
    }
}




// ******************************************************************** //
// Page Load/Unload                                                     //
// ******************************************************************** //

function pageInit() { // Page Load

        Event.observe(document.body, 'click', function(event) {
            var element = Event.element(event);
            // If the Flash item has been clicked then don't run the pageClick function to
            // close the Flash Drop Down. This fixes the issue in Safari on Mac where
            // observing the document doesn't work properly
            
            if ('EMBED' != element.tagName)
                if (isReady() && isFlashReady()) {
            //        insideSWF().pageClick()
                }   
        });
       
        if($('stafLink')){
       
            $('stafLink').onclick = function() {
                stafToggle();
            };
        }
        
        $('btnCancel').onclick = function() {
            stafToggle();
        };       
         $('btnClose').onclick = function() {
            stafToggle();
        };   
            
        if($('shareLink')){
        
            $('shareLink').onclick = function() {
                shareToggle();
            };
        }         
   
         $('btnCloseShare').onclick = function() {
            shareToggle();
        };   
            
        
        jsReady = true;
    
        contentAppear = "";
        contentFade = "";        
        
        recommendedLinks();  // Initialise the footer links - sets observe events
     
	    addFlashContent(); // Load in the Flash File
        
        // Set the content area to blank
        var contentArea = $('contentArea')
        contentArea.innerHTML = "";
        
        
}
// Fade in/out the Send to a Friend panel
function stafToggle(){
    
    if (shareDisplay){
        if ((browserArray.join().indexOf(browser)) == -1){
            new Effect.Fade($('share'), {duration: 0.5, from: 1.1, to : 0.0});
        }else{
            $('share').hide();
        }
        shareDisplay = false;
    }
    
    if (stafDisplay){
        if ((browserArray.join().indexOf(browser)) == -1){
            new Effect.Fade($('staf'), {duration: 0.5, from: 1.1, to : 0.0});
        }else{
            $('staf').hide();
        }
        stafDisplay = false;
    }else{
        $('stafForm').show();
        $('stafConfirm').hide();
        
        if ((browserArray.join().indexOf(browser)) == -1){
            
            
            new Effect.Appear($('staf'), {duration: 0.5, from: 0.0, to : 1.0});
            

            
        }else{
            $('staf').show();
        }
        stafDisplay = true;
        pageRef = getQueryParamValue("")
        if($('siteURL')){
            var siteURL = $('siteURL').value
        }
        if (pageRef != "" && pageRef != " " && pageRef != "%20"){
             $('txtURL').value = siteURL+"/insideDyson/#"+pageRef
        }        
    }
}

// Fade in/out the Share panel
function shareToggle(){

    if (stafDisplay){
        if ((browserArray.join().indexOf(browser)) == -1){
            new Effect.Fade($('staf'), {duration: 0.5, from: 1.1, to : 0.0});
        }else{
            $('staf').hide();
        }
        stafDisplay = false;
    }

    if (shareDisplay){
        if ((browserArray.join().indexOf(browser)) == -1){
            new Effect.Fade($('share'), {duration: 0.5, from: 1.1, to : 0.0});
        }else{
            $('share').hide();
        }
        shareDisplay = false;
    }else{
        if ((browserArray.join().indexOf(browser)) == -1){
            new Effect.Appear($('share'), {duration: 0.5, from: 0.0, to : 1.0});
            
        }else{
            $('share').show();
        }
        shareDisplay = true;
        
        //alert($('siteURL').value)
        var siteURL = $('siteURL').value
        pageRef = getQueryParamValue("")
        
        if (pageRef == ""){
            pageRef = $('txtTag').value
        }
        if (pageRef != "" && pageRef != " " && pageRef != "%20"){
             $('txtURLShare').value = siteURL+"/insideDyson/#"+pageRef
        }
        
    }
}


function hideStaf(){
  if (stafDisplay){
        new Effect.Fade($('staf'), {duration: 0.5, from: 1.1, to : 0.0});
        stafDisplay = false;
    }else{
        $('staf').hide();
    }  
}

function hideShare(){
  if (stafDisplay){
        new Effect.Fade($('share'), {duration: 0.5, from: 1.1, to : 0.0});
        shareDisplay = false;
    }else{
        $('share').hide();
    }  
}


function pageUnload(){
    // Clear the content area
    var contentArea = $('contentArea')
    contentArea.innerHTML = "";    
}

// ******************************************************************** //
// Functions for Flash Movie                                            //
// ******************************************************************** //

function isReady() {
    return jsReady;
}
function isFlashReady() {
	return flashReady;
}
function ready() {
	if (isReady() && isFlashReady()) {
		return true;
	}else{
		return false;
	}
}
	
function insideSWF() {
	var movieName = 'insideJSObj';
	 
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function disableUI(){
    disableLinks = true;
}

function enableUI() {
    disableLinks = false;
}

function flashIsReady() {
	flashReady = true;
}

function sendToActionScript(value){
    if (ready()){
        insideSWF().sendToActionScript(value);
    }   
}

function showCategory(catID) {
	if (ready()){
	    insideSWF().showCategory(catID);
	}
}
function pageClick(){
    insideSWF().pageClick()
}
function openStory(aID) {
    
	if (ready()){
	    insideSWF().openStoryFromTag(aID)
    }
}

// ******************************************************************** //
// Back and Forward functionality                                       //
// ******************************************************************** //


if (browserArray.join().indexOf(browser) == -1){

    Event.observe(window, 'load', function() {
            dhtmlHistory.initialize();
            dhtmlHistory.addListener(historyChange);
         
    });
}

var historyChange = function(newLocation, historyData) {

    var pageSplit = ""
    var pageSplitArray
    var splitChar
    
    if (browser.indexOf("safari") != -1){
        splitChar = safariSplit
    }else{
        splitChar = "#"
    }
    
    if (newLocation.indexOf(splitChar)>-1){
        if (browser.indexOf("safari") != -1){
            pageSplitArray = newLocation.split(splitChar)
        }else{
            pageSplitArray = newLocation.split(splitChar)
        }
        pageSplit = pageSplitArray[0]
    }else{
        pageSplit = newLocation
    }
   
    if (pageSplit != "" && pageSplit != " " && pageSplit != "%20" && pageSplit != "undefined"){
        
    }else{

        if($('newloc')){
        
            $('newloc').value = newLocation;
          
            // If not opening a new article (i.e. there is no Tag) then
            // we can run the hideContent function - there is a check in this to make sure it is not
            // already running as it will run when requested by the Flash file and then as soon as the
            // URL has changed
            if ($('newloc').value == " " || $('newloc').value == "" ){
                hideContent();
                if (isReady() && isFlashReady()) {
                    insideSWF().closeStory();
                }
            }else{
            
                var contentArea = $('contentArea')
                if(contentArea.innerHTML != ""){
                    insideSWF().closeStory();
                }
                
            }
        }
    }
}
       

function addPage(page){
    window.location.hash = page;
}  

    

Event.observe ( window, "load", function(){ pageInit(); } );
Event.observe ( window, "unload", function(){ pageUnload(); } );


// ******************************************************************** //
// Observe Functions for links                                          //
// ******************************************************************** //

// Recommended Links on footer
function recommendedLinks(){
    var links = document.getElementsByTagName("a");
    for (var i=0; i < links.length; i++) {
        if (links[i].rel.match("categoryResult")) {
            links[i].onclick = function() {
            
                this.href = "javascript:void(0);"
                var title_search = this.id.split("_");
                showCategory(title_search[1]);
            }
        }
    }
}
 
// Sets a watcher for the Wiki Links
function wikiLinks(){

    var wikiLinks = document.getElementsByTagName("a");
   
    for (var i=0; i < wikiLinks.length; i++) {
        if (wikiLinks[i].className.match("wikiLink")) {
        
            wikiLinks[i].onclick = function() {
            
                tagName = this.href.split("=");
                this.href = "javascript:void(0);"
                tagName = tagName[1]
                openStory(tagName);
            }
        }
    }
    if($('stafLink')){
        $('stafLink').onclick = function() {
            stafToggle();
        };
    }  
    if($('shareLink')){
    
        $('shareLink').onclick = function() {
            shareToggle();
        };
    }             
    $('stafSend').onclick = function() {

        if (typeof pageTracker != "undefined"){
            pageTracker._trackPageview("Send to a Friend: "+$('txtTag').value);
            pageTrackerExternal._trackPageview("Send to a Friend: "+$('txtTag').value);
        }

    
        var data = $('txtFrom').value+"|"+$('txtTo').value+"||"+$('txtTag').value

        var url = "staf.asp?"+data
        
        
        var myAjax = new Ajax.Request (url,{
            parameters: data,
            method:'post',
            onSuccess: function(validate){
                if (validate.responseText != ""){
                    var errMsg = validate.responseText;
                        errMsg = errMsg.split("|")
                        $('errFrom').innerHTML = errMsg[0];
                        $('errTo').innerHTML = errMsg[1];
                        $('errSubject').innerHTML = errMsg[2];
    
                    
                }else{
          
                    new Effect.Fade($('stafForm'), {duration: 0.2, from: 1.1, to : 0.0, afterFinish:function(){
                    new Effect.Appear($('stafConfirm'), {duration: 0.2, from: 0.1, to : 1.1});
                    }});
                }
                
            }
        });
    };    
    
    
    // Initalise the External Links script to set external links to open in new window
    externalLinks();
}

// ******************************************************************** //


/* Functions for Flash Movie */
function setSlideStatus(){
    $('slideStatus').value = "open";
    $('contentArea').style.height = "100%";
}
function setSlideStatusClose(){
    $('slideStatus').value = "closed";
        var contentArea = document.getElementById('contentArea')
        contentArea.innerHTML = "";    
}

function closeParent(){
    if (browserArray.join().indexOf(browser) == -1){
        window.location.hash = " ";
    }
}
function hideContent(){

    hideStaf();
    hideShare();
   
    // Need to split the URL by the Hash
    if (browserArray.join().indexOf(browser) == -1){
    
   
        var pageRef =  new String(document.location.href);
        var pageRefArray
        var hashAddress = ""
        var splitChar
        var childSplit
      
        splitChar = "#"
        
        if (pageRef.indexOf(splitChar)>-1){
          
            var totalHashes = pageRef.split(splitChar).length;
            pageRefArray = pageRef.split("#")
            
            // Because Safari encodes the URL, we will only have one %23 (and one # rather than 2 #'s)
            if (browser.indexOf("safari") != -1){
               
                if (pageRefArray[1].indexOf(safariSplit)>-1){
                
                    childSplit = pageRefArray[1].split(safariSplit)
                    hashAddress += "#"+childSplit[0]
                }else{
                    hashAddress = " "
                }
            }else{
                for (i=1;i<=totalHashes-2;i++){
                    hashAddress += "#"+pageRefArray[i]
                }
            }

            hashAddress = hashAddress.substring(1,hashAddress.length)
            
        }
        
        
        if (hashAddress == ""){
            hashAddress = " "
        }
    }
    var contentArea = $('contentArea');
    // if the browser name appears in the browser array list
    // then just set the display to none   
    if (browserArray.join().indexOf(browser) != -1){ 
    
     
        $('contentHolder').style.display = 'none';
        contentArea.innerHTML = "";
        $('contentHolder').style.display = 'block';
    }else{
    
   
        // The transAction value determines if we can run the fade
        // When first loaded, the value is set to transComplete to allow it
        // to be run. Whilst running it is then set to inProgress to stop any further
        // iterations of this running.
        // Once complete it then sets it back to transComplete to allow further
        // fades to run.
        
        //if ($('transAction').value == "transComplete"){
        //    $('transAction').value = "transInProgress"
            window.location.hash = hashAddress;

            contentFade = new Effect.Fade('contentHolder', {duration: 0.15, from: 1.0, to : 0.1});

            new PeriodicalExecuter(function(pe) {
                contentArea.innerHTML = "";
                contentAppear = new Effect.Appear('contentHolder', {duration: 0.15, from: 0.1, to : 1.1});
                pe.stop();
                $('transAction').value = "transComplete"
            }, 0.15); 
       // }
    }
}


function displayContent(content,tag) {
   if (typeof pageTracker != "undefined"){
        pageTracker._trackPageview("Inside Dyson: "+tag);
        pageTrackerExternal._trackPageview("Inside Dyson: "+tag);
    }


    // Hide Send to a Friend when moving between articles
    if (stafDisplay){
        stafToggle();
    }

    if ($('txtTag')){
        $('txtTag').value = tag;
    }
    // Run AJAX function for tracking purposes
    var url = "tracking.asp?"+tag
    var myAjax = new Ajax.Request (url);
	            
                

    // need to add in the Tag Ref and pass through to location.hash
    
    if (browserArray.join().indexOf(browser) == -1){

        var pageRef =  new String(document.location.href);
        var pageRefArray
        if (pageRef.indexOf("#")>-1){
            pageRefArray = pageRef.split("#")
            
            if (pageRefArray[1] == tag){
                tag = pageRefArray[1]
            }else{
                if (pageRefArray[1] != "%20" && pageRefArray[1] != " " && pageRefArray[1] != "undefined"){
                    tag = pageRefArray[1]+"#"+tag
                }
            }
        }
        window.location.hash = " ";     // Used to reset the history so that when opening a child article,
        window.location.hash = tag;      
    }
     
   
    var contentArea = $('contentArea');

    
    if (browserArray.join().indexOf(browser) != -1){
        contentArea.innerHTML = "<p></p><p>"+content+"</p>";
        $('contentHolder').style.display = 'block';
        wikiLinks();
    }else{
        contentFade = new Effect.Fade('contentHolder', {duration: 0.15, from: 1.0, to : 0.1});
        
        new PeriodicalExecuter(function(pe) {
            contentArea.innerHTML = "<p></p><p>"+content+"</p>";
            pe.stop();
        }, 0.15); 
        
        new PeriodicalExecuter(function(pe) {
            if (browserArray.join().indexOf(browser) > -1){
                $('contentHolder').style.display = 'block';
            }else{
                contentAppear = new Effect.Appear('contentHolder', {duration: 0.15, from: 0.1, to : 1.1, afterFinish:wikiLinks});
            }
            pe.stop();
        }, 0.15);
    }
}


function search(){
}

function message(content){
    //alert(content);
}
