/* Copyright © FeONIC plc, Parthian Systems (Development) - 2008. All Rights Reserved.
 * v2 - 14th September - loadAccordians now uses friendly URLs */



function FeatureSlider(container, events, vertical, IE6HeightHack) {
    var obj = this;
        obj.vertical = vertical; /* Parthian boolean to indicate direction */
    obj.container = container = $(container);
    obj.events = events || {};
        // Parthian - allow elements other than singles to be visible
        if (obj.vertical)
      obj.container.setStyle({position:'relative',overflow:'visible'});
    else
      obj.container.setStyle({position:'relative',overflow:'visible'});

        obj.items = container.childElements();
    obj.index = 1;    // Get the width and height of the container element
    obj.dimensions = obj.container.getDimensions();    // Build a helper box within the container
        //alert (obj.dimensions.height);
        if (IE6HeightHack != 0)
          obj.dimensions.height = IE6HeightHack; // In IE6 the height from getDimensions is wrong. A hack will have to do for now

    obj.helper = new Element('div', {className:'feature-slider-helper'});
        // Parthian The vertical selection needs tp have a height big enough for all selections and make overflow visible
        if (obj.vertical)
      obj.helper.setStyle({width:obj.dimensions.width+'px', height:(obj.dimensions.height*obj.items.length)+'px', overflow:'visible'});
    else
      obj.helper.setStyle({height:obj.dimensions.height+'px', width:(obj.dimensions.width*obj.items.length)+'px', overflow:'visible'});
    obj.helper.morph = obj.helper.morph||obj.helper.setStyle; // If scripaculous is loaded, we can animate. Otherwise, use prototype.
    obj.container.appendChild(obj.helper);    // Build container boxes for each element to be fitted in the container.
    // Hierarchy: 'container' -> 'helper' -> 'itembox' -> 'item'
    obj.items.each(function(item) {
            var itembox = new Element('div', {className:'feature-slider-item-box'});
                        if (obj.vertical) // Parthian visible overflow on vertical
                          itembox.setStyle({height:obj.dimensions.height +'px', width:obj.dimensions.width+'px', overflow:'visible'});
            else
                          itembox.setStyle({height:obj.dimensions.height +'px', width:obj.dimensions.width+'px', overflow:'visible', float:'left'});
            itembox.appendChild(item);
            obj.helper.appendChild(itembox);
        });
        if(typeof(obj.events.onLoad)=='function') obj.events.onLoad(obj);
    if(typeof(obj.events.onChange)=='function') obj.events.onChange(obj,1);
        obj.go = function(i)
                   {
                   if(i<1||i>obj.items.length) return;
                   if(typeof(obj.events.onChange)=='function')
                     obj.events.onChange(obj, i);
                         if (obj.vertical) { // Move the vertical up/down
                              obj.helper.morph({marginTop:((i-1)*obj.dimensions.height*-1)+'px'}, {duration:.3});
                           obj.index=i;
                         } else {
                              obj.helper.morph({marginLeft:((i-1)*obj.dimensions.width*-1)+'px'}, {duration:.3});
                           obj.index=i;
                           //obj.helper.setStyle({ border: '1px solid #33CCFF'} );
                         }
                   }
    obj.first = function(){obj.go(1);}
    obj.last = function(){obj.go(obj.items.length);}
    obj.previous = function(){obj.go(obj.index-1);}
    obj.next = function(){obj.go(obj.index+1);}
}



/* http://www.refresh.dk/topic/javascript/ */
function showSliderImage (e, ethis) {
/* Horizontal Slider - use last chars after UNDERSCORE as indicator of the column.
  1st part (match) needs a number (or unique part) to be unique as two images CAN exist in each column */
var id = ethis.id;

//patt=new RegExp("[a-zA-Z]+"); // grab 1st characters
//start = patt.exec(id);
//patt=new RegExp("[0-9]+"); // then column value from end...
//end = patt.exec(id);

var pattern = id.split("_");
var column = parseInt(pattern[1]);
var match = pattern[0];

$$('.sliderimgBright').each(function(box) {
  box.className = "sliderimgDull";
  /*
        box.style.border = "2px solid transparent";
  box.style.opacity = "0.7";
  box.style.filter = "alpha(opacity=70)"; */   } );

var sliderimg = $(match + 'img_' + column);  // e.g. dtimg_1
sliderimg.className = "sliderimgBright";
/*
sliderimg.style.border = "2px solid #3CF";
sliderimg.style.opacity = "1.0";
sliderimg.style.filter = "alpha(opacity=100)";
*/
fs.go(column);
return false;
}

/* ------ End Slider ----- Start Popup ------   */

function showPicture (leafletName) {
  document.body.style.cursor = "wait";
  picture_object = new Image();
  // First setup Event handler (before setting src that will fire event).
  // Must use onload not onLoad for some reason... but onLoad did fire event when i.onLoad=theFunc();  method was used
  // cannot pass parameter unless the fancy function(e) method is used
  // function(e) { thefunction(e); return false; }; // where return false removes param from memory (I think)
  picture_object.onload = function (leafletName) {displayPicture(leafletName); return false; };
  picture_object.src=leafletName;
  //picture_object.src="http://parthian.webfactional.com/data/" + username + "/" + leafletName;
}

function displayPicture(leafletName) {
  var leafletDIV;

  var boxWidth = picture_object.width + 60; // space for Close button if a small image
  var boxHeight = picture_object.height + 65;
  var closePosnL = (picture_object.width / 2) - 20;
  var closePosnR = closePosnL + 20;

  leafletDIV = "<div class='xmlsave-box' id='foldout-box' style='z-index:1000; position:absolute; top:40px; left:10px; height:" + boxHeight + "px; width:" + boxWidth + "px;'>\n\
<button type='button' style='position:absolute; top: 5px; left:" + closePosnL + "px; right:" + closePosnR + "px; z-index:1001;' onclick='javascript:close_popup(\"foldout-box\");'>Close</button>\n\
<img id='page3' height='" + picture_object.height +  "' width='" + picture_object.width +  "' src=" + picture_object.src + " style='position:absolute; top:40px; left:30px; display:block;' />\n\
<button type='button' style='position:absolute; bottom: 5px; left:" + closePosnL + "px; right:" + closePosnR + "px; z-index:1001;' onclick='javascript:close_popup(\"foldout-box\");'>Close</button>\n\
</div>";

  var obj = document.getElementById('leaflet');
  if (leafletName != "") {
    obj.innerHTML = leafletDIV;
    obj.focus();
  }
  obj.style.visibility = "visible";
  obj.style.display = "inline";
  show_popup("foldout-box", "");
}

function show_popup(sID, response) {
  //document.body.style.color = 'red';
  //document.body.style.filter="alpha(opacity=30)";
  //document.body.style.opacity = "0.8";
  if(sID!="xmlsave-box")  close_popup("xmlsave-box");
  if(sID!="foldout-box")  close_popup("foldout-box");
  var obj = document.getElementById(sID);
  obj.style.visibility = "visible";
  obj.style.display = "inline";

  // Should really add Error handlers to catch failures and reset cursor
  document.body.style.cursor = "auto";
}

function showLeaflet(sID, leafletName) {
  var leafletDIV;
  leafletDIV = "<div class='xmlsave-box' id='foldout-box' style='position:absolute; height:670px; width:940px; top:30px; left:70px;'>" +
"<img id='page1' height='663' width='466' src='" + leafletName + "' style='position:absolute; top:10px; left:470px; display:block;' />" +
"<button type='button' style='position:absolute; z-index:1001' onclick='javascript:close_popup(\"foldout-box\");'>Close</button></div>";

  if(sID!="leaflet")  close_popup("leaflet");
  var obj = document.getElementById(sID);
  if (leafletName != "") {
    obj.innerHTML = leafletDIV;
    obj.focus();
  }
  obj.style.visibility = "visible";
  obj.style.display = "inline";
}


function close_popup(sID) {
  var obj = document.getElementById(sID);
  if (obj != null) {
    obj.style.visibility = "hidden";
    obj.style.display = "none";
  }
 //$('wrap').style.filter = "alpha(opacity=100)";
 //$('wrap').style.opacity = "1.0";
}

/* -------  End Popup ---- Start Fader -----  */

var hqCount = 1; // FADER function used with header quotes
var MAXQUOTE = 1; // Set by sitewide Django code to maximum number of quotes
// http://snippets.dzone.com/user/peter/tag/scriptaculous
var fader = { // Testimonials
  startup: function() {
    new Effect.Appear('hq' + hqCount, {duration:0.5});
    new PeriodicalExecuter(fader.cycle, 10); // seconds
   },
  cycle: function() {
    new Effect.Fade('hq' + hqCount, { duration:0.5, queue: 'end', // queue fix for FF2.00.18
         afterFinish: function() {
           if (hqCount == MAXQUOTE) // Set by sitewide to cope with new quotes
         hqCount = 1
       else
         hqCount++;
           new Effect.Appear('hq' + hqCount, {duration:0.5, queue: 'end'});
          }
         })
   }
 }


 /* ------ Rollovers ------------ */

var roID = null; // module var to let moverollover run quicker (removes many $)

 function mouseX(evt) {
if (evt.pageX)
  return evt.pageX;
else if (evt.clientX)
   return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
else return 0;
}

function mouseY(evt) {
if (evt.pageY)
  return evt.pageY;
else if (evt.clientY)
   return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
else return 0;
}

function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
  do {
  curleft += obj.offsetLeft;
  curtop += obj.offsetTop;
  } while (obj = obj.offsetParent); // possible = instead of == is deliberate
 }
 return [curleft,curtop];
}
/*
function detectRollover (e, ethis, rolloverID) {
// not currently used
  var targ;
  if (!e)  e = window.event;
  if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
  //alert ("targ  " + targ.id + "  rolloverID " + rolloverID);

  var xy = findPos (ethis);
  xy[0] = xy[0] - ethis.width;
  var x = mouseX (e);
  var y = mouseY (e);
  //alert (findPos (ethis) + " " + ethis.width + " " + ethis.height + " " + x + " " + y);
  if ( (x < xy[0] || x > (xy[0] + ethis.width)) ||
      (y < xy[1] || y > (xy[1] + ethis.height)) ) {
          //alert ('Hiding ' + x + " " + y);
    $(rolloverID).hide();
          ethis.className='mosaicDull';
          //alert ('out');
          return false;
   }
 // not currently used
}
*/
function displayRollover (event, rollSize) {
// alternative that doesn't set class to MosaicBright which resets size to 178 from mini size...

wrapperResizedOffsetLeft = $$('.wrapper')[0].offsetLeft; // Don't do this on mousemove too slow
killRollover();

var x = mouseX (event) - wrapperResizedOffsetLeft;
//alert (x); // this gives position within wrapper
if (x > 620) // Magic Number - to Right of this place rollover on left
  wrapperResizedOffsetLeft = wrapperResizedOffsetLeft + rollSize;
x = mouseX (event) - wrapperResizedOffsetLeft; // slightly inefficient but reset to correct location
var y = mouseY (event);
roID.style.top = (y + 10) + 'px';
roID.style.left = (x + 15) + 'px';
roID.appear({duration: 1.0, queue: { position: 'end', limit:4, scope: 'rollover'} });
 }

function hideRollover (rollover) {
 // remove the old rollover 1st - don't allow to run in parallel
 $(rollover).fade({duration: 0.0, queue: { position: 'end', limit:4, scope: 'rollover'} });
 }

function showMiniRollover (event, ethis, rolloverID) {
  // Used on Home page - doesn't use mosaicDull / Bright and has smaller rollover for RHS calculations
  roID = $(rolloverID); // set the module var
  if (ethis.className == 'homeminiwide')
    displayRollover (event, 245); // the wider rollovers
  else
    displayRollover (event, 145);
  return false;
 }

function showRollover (event, ethis, rolloverID) {
  // Products now uses Sprites so has a more complicated class - append the mosaicBright which should override mosiacDull
  ethis.className= ethis.className + ' mosaicBright';
  roID = $(rolloverID); // set the module var
  displayRollover (event, 245); // This value is width of rollover plus margin - ideally get this from Style
  return false;
 }

function moveRollover (event, rolloverID) {
// mouseX/Y and $() could be written with external vars to speed this up a little.
var x = mouseX (event) - wrapperResizedOffsetLeft;
var y = mouseY (event);
roID.style.top = (y + 5) + 'px';
roID.style.left = (x + 15) + 'px';
 }


function killRollover () {
  // make sure they are all dead in case any aren't hidden automatically.
  $$('.rollover').each(Element.hide);
  $$('.rolloverWide').each(Element.hide);
  $$('.rolloverImage').each(Element.hide);
  $$('.rolloverWImage').each(Element.hide);
}


/* --------- End Rollovers -----  Start Accordion --------  */

 function openProducts () {
 // called from anchor links that require non-default accordion to open
 pageTracker._trackEvent('Products', 'FromHomePics', ''); // 20/1/10 From Home page this runs to open Products. Count these.
 verticalAccordion.activate($$('#vertical_container .accordion_toggle')[1]);
 }

// http://stickmanlabs.com/
function loadAccordions() {
// Make the Accordion a fixed height and then use Anchors to move to specific point in contents
// so make all 'pages' height pixels in size (plus some padding)

  verticalAccordion = new accordion('vertical_container',{defaultSize : {height: 396, width : 846}, resizeSpeed : 4, onActivate: accordCallback, onEvent: 'click' });

  // Open first one unless link contains pa anchor
  //if (location.hash.indexOf ('flat-panel-speakers') > 0) {
  if(location.hash in {'#flat-panel-speakers':'0', '#f13Info':'0', '#f4Info':'0', '#marine-speakers':'0', '#subwoofer':'0', '#f1MInfo':'0', '#f110Info':'0', '#f230Info':'0',  '#wwInfo':'0'}) {
    verticalAccordion.activate($$('#vertical_container .accordion_toggle')[1]);
  } else {
    verticalAccordion.activate($$('#vertical_container .accordion_toggle')[0]);
  }
}

// You can hide the accordions on page load like this, it maintains accessibility
// Special thanks go out to Will Shaver @ http://primedigit.com/
function closeAccordions () {
        var verticalAccordions = $$('.accordion_toggle_active'); // should this be _active? wasn't originally
        verticalAccordions.each(function(accordion) {
                $(accordion.next(0)).setStyle({
                  height: '0px'
                });
        });
}

function accordCallback (e) {
//alert ("Callback from " + e.id + "  Name is " + e.name);
  // code runs when the accordion is clicked But not on a link
  killRollover ();
}

/* ------- End Accordions ----- Clicks -------- */

function handleClick (e, ethis) {
  // Cope with clicks on Accordion ToggleBar. Cope with simple open/close and further links to specific 'pages'

  killRollover (); // Make sure any dangling rollovers are dealt with

  // If Clicked elements Accordion is closed open it.
  if (ethis.className == "msA")
    if ($$('.accordion_content')[0].style.height == '0px') {
     verticalAccordion.activate($$('#vertical_container .accordion_toggle')[0]);
         //document.location.href = ethis.href;
         //return true;
         }


  if (ethis.className == "paA")
    if ($$('.accordion_content')[1].style.height == '0px') {// 2nd Accordion tested
      verticalAccordion.activate($$('#vertical_container .accordion_toggle')[1]); // 2nd accordion opened
         //document.location.href = ethis.href;
         //return true;
    }

  // Bubbling cancelled to prevent click of links bubbling up to Accordion causing endless toggles.
  // good event info http://www.webdevelopersjournal.com/articles/jsevents2/jsevents2.html - event.returnValue=true;
  if (!e)
    e = window.event;
  e.cancelBubble = true;
  if (e.stopPropagation)
    e.stopPropagation();
  //return true;
}