var agentName="";
try
{
    agentName = navigator.userAgent.toLowerCase();
}
catch(e){}
var isMac = ( agentName.indexOf('mac') != -1 );
var isIE6 = ( agentName.indexOf('msie 6.0') != -1 );
var isFireFox = ( agentName.indexOf('firefox') != -1 );
var isSafari = ( agentName.indexOf('safari') != -1 );

// flash paragraph background 
var flashPara;

// Codes in crumbtrail to be replaced with correct case
var caseReplace = '::AC::AC3CN::ARC::AS::aX1::aX2::aX3::aX4::BFH::BR::BUH::CAB::CFH::CFP::CFS::CPD::CS::CVP::CXL::CXLS::DAB::DE::DLR::DTR::DuoHeat::';
caseReplace += 'DX::DX4123::DX4124::DXFF::DXUF20::DXUF30T::DXLWP::ECO::EPX::EVS::FXL::FXPH::FX20::FX20VE::FX20VL::HAW::HS::IAB::KX::LA::LAS::LI::ME::';
caseReplace += 'MEK::MEKR::MER::MIR40::MK1::MPH::MR::MS::MT::OFX::OPH::PDF::PDFs::PLX::PFH::PS::RF::RPX::RXPWIF::PX::QXD::SCH::SCHRI::SCx::SI::SLR::';
caseReplace += 'SP4::SP5::SP6::SP8::SP9::SU::SUTP::TE::TEH::TER::TR::TT::TUX::WB::WF::WI::XL::XLS::XLS6::XL6::';

// Specific words to replace
var wordReplace = new Array();
wordReplace[0] = new Array('4zone','4 Zone ');
wordReplace[1] = new Array('DTR ECO','Daytona');
wordReplace[2] = new Array('Undertile','Under-tile');
wordReplace[3] = new Array('Under Tile','Under-tile');
wordReplace[4] = new Array('Tipsey','Tipsy');
wordReplace[5] = new Array('Duel','Dual');
wordReplace[6] = new Array('Inset Fires','Inset and Freestanding Fires');
wordReplace[7] = new Array('SUTP Ranges','SU SUTP ranges');
wordReplace[8] = new Array('Tp Ranges','SU SUTP ranges');
wordReplace[9] = new Array('Scxrange','SCx range');
wordReplace[10] = new Array('LI TERplus','LI TER+');
wordReplace[11] = new Array('SI TEH 50-130kW','SI TE 50-130kW');
wordReplace[12] = new Array('SI TE','SI TE 17-37kW range');
wordReplace[13] = new Array('Mini XL XL6','XL6/XLS6 Range');
wordReplace[14] = new Array('Help ME Choose','Help Me Choose');
wordReplace[15] = new Array('Az','A-Z');
wordReplace[16] = new Array('Vector Vr Range','CXD Range');
wordReplace[17] = new Array('Exp Range','EPX Range');
wordReplace[18] = new Array('Glass Fronted Xx Range','Girona Range');
wordReplace[19] = new Array('Metal Fronted Xx Range','Monterey Range');
wordReplace[20] = new Array('Exhibitions Events','Exhibitions &amp; Events');

// Press Centre words to replace
var pcReplace = new Array();
pcReplace[0] = new Array('C ','Corporate ');
pcReplace[1] = new Array('Ih ','Installed Heating ');
pcReplace[2] = new Array('Fs ','Fires and Surrounds ');
pcReplace[3] = new Array('Kb ','Kitchens and Bathrooms ');
pcReplace[4] = new Array('Ph ','Portable Heating ');
pcReplace[5] = new Array('Mh ','Miscellaneous Heating ');
pcReplace[6] = new Array('Wh ','Water Heating ');
pcReplace[7] = new Array('Rh ','Renewable Heating ');
pcReplace[8] = new Array('Ch ','Commercial Heating ');

String.prototype.format = function()
{
    var w = this.split('_'); // Split out words
    var cr = caseReplace.split('::');
    for ( var i = 0; i < w.length; i ++ )
    {
        // Initial upper case each word
        w[i] = w[i].substr(0,1).toUpperCase() + w[i].substr(1, w[i].length - 1 );
        
        // Do specific case formatting
        if ( caseReplace.toLowerCase().indexOf( '::' + w[i].toLowerCase() + '::' ) != -1 )
        {
            // Loop through the replace words and use it when found
            for ( var j = 0; j < cr.length; j ++ )
            {
                if ( cr[j].toLowerCase() == w[i].toLowerCase() )
                {
                    w[i] = cr[j];
                    break;
                }
            }
        }
        
        // Remove .htm
        if ( w[i].indexOf('.htm') != -1 )
        {
            w[i] = w[i].split('.htm')[0];
        }
    }
    
    // Build the return string
    var rs = w.join(' ');
    
    // If we're in the Press Centre
    if ( location.pathname.indexOf('press_centre') != -1 )
    {
        // Check through the words to replace
        for ( i in pcReplace )
        {
            // Find index of string to replace if found
            var index = rs.toLowerCase().indexOf( pcReplace[i][0].toLowerCase() );
            
            // If the string's found
            if ( index != -1 )
            {
                // Rebuild the string with the replacement word
                var ns = rs.substr(0, index) + pcReplace[i][1] + rs.substr( (index + pcReplace[i][0].length ), rs.length );
                rs = ns;
                break;
            }
        }
        // Check through the words to replace
        for ( i in wordReplace )
        {
            // Find index of string to replace if found
            var index = rs.toLowerCase().indexOf( wordReplace[i][0].toLowerCase() );
            
            // If the string's found
            if ( index != -1 )
            {
                // Rebuild the string with the replacement word
                var ns = rs.substr(0, index) + wordReplace[i][1] + rs.substr( (index + wordReplace[i][0].length ), rs.length );
                rs = ns;
                break;
            }
        }        
    }
    else
    {
        // Check through the words to replace
        for ( i in wordReplace )
        {
            // Find index of string to replace if found
            var index = rs.toLowerCase().indexOf( wordReplace[i][0].toLowerCase() );
            
            // If the string's found
            if ( index != -1 )
            {
                // Rebuild the string with the replacement word
                var ns = rs.substr(0, index) + wordReplace[i][1] + rs.substr( (index + wordReplace[i][0].length ), rs.length );
                rs = ns;
                break;
            }
        }
    }
    
    return rs;
}

function writeCrumbtrail()
{
    // Get the location path 
    var lp = location.pathname;
    if ( lp.indexOf('index.htm') != -1 )
    {
        lp = lp.split('index.htm')[0];
    }
    // Get the folders
    var f = lp.split('/');
    
    if ( f.length > 2 )
    {
        var c = '<p><b>You are here:</b> <a href="/">Homepage</a>';
        var a = '/';
        for ( var i = 0; i < f.length; i ++ )
        {
            if ( f[i] != '' )
            {
                a += f[i];
                // If folder then add trailing slash
                if ( f[i].indexOf('.htm') == -1 )
                {
                    a += '/';
                }
                // Add to the string
                c += ' &gt; <a href="' + a + '">' + f[i].format() + '</a>';
            }
        }
        c += '</p>';
        // Only show crumbtrail if deeper than home
        if ( f.length > 2 )
        {
            var d = document.getElementById('crumbtrail');
            d.innerHTML = c;
            d.style.display = 'block';
        }
    }
}
function attachEvents()
{
	document.getElementById('search_term').onmousedown = function()
	{
	    this.value = '';
	    this.focus();
	}
	document.getElementById('search_term').onblur = function()
	{
	    if ( this.value == '' )
	    {
	        this.value = 'Keyword Site Search';
	    }
	}
	if ( document.getElementById('panel_list') )
	{
	    var d = document.getElementById('panel_list');
        var ul = d.getElementsByTagName('ul');
        if ( ul.length )
        {
            for ( var i = 0; i < ul.length; i ++ )
            {
                if ( ul[i].className == 'nav_panel' )
                {
                    // Get the href from the more link if it exists
                    var li = ul[i].getElementsByTagName('li');
                    for ( var j = 0; j < li.length; j ++ )
                    {
                        if ( li[j].className == 'more' && li[j].firstChild )
                        {
                            ul[i].href = li[j].firstChild.href;
                        }
                    }
                    if ( ul[i].href )
                    {
                        // Interative
                        ul[i].onmouseover = function()
                        {
                            this.className += ' over';
                            this.style.cursor = 'pointer';
                        }
                        ul[i].onmouseout = function()
                        {
                            this.className = 'nav_panel';
                        }
                        // On click
                        ul[i].onmousedown = function()
                        {
                            window.location = this.href;
                        }
                    }
                }
            }
        }
	}
}
function emContentImages()
{
    // Calculate offset for IE6 and Firefox for when the font size has been
    // increased prior to the page loading. Uses a hidden span tag to calculate
    // the size difference and then increase
    if ( isFireFox || isIE6 )
    {
        // Height
        //var h = document.getElementById('text_size').offsetHeight;
        // Default height
        //var dh  = isFireFox ? 19 : 18;
        // Increase
        //var inc = h - dh;
        // Adjustments per browser [height, width]
        //var adj = new Array();
        //if ( isFireFox )
        //{
        //    adj[0] = [1,1];
        //    adj[4] = [1,0.913];
        //    adj[9] = [0.8165,0.8165];
        //}
        //else
        //{
        //    adj[0] = [1,1];
        //    adj[7] = [0.86,0.857];
        //    adj[14] = [1,0.75];
        //}
        
        //document.getElementById('search_term').value = inc;
        
        var img = document.getElementById('layout').getElementsByTagName('img');
        if ( img.length )
        {
            for ( var i = 0; i < img.length; i ++ )
            {
                img[i].style.height = ( img[i].offsetHeight / 16 ) + 'em';
                //alert( 'height: ' + adj[inc][0] + ', width: ' + adj[inc][1] );
                //img[i].style.height = ( ( img[i].offsetHeight * adj[inc][0] ) / 16 ) + 'em';
                //img[i].style.width  = ( ( img[i].offsetWidth  * adj[inc][1] ) / 16 ) + 'em';
            }
        }
    }
}
function initRollovers()
{
  if ( document.images )
  {
    var preLoad = new Array();
    var tempSrc;
    for (var i = 0; i < document.images.length; i ++ )
    {
      // Only add rollover to images with the classname 'rollover'
      if ( document.images[i].className == 'rollover' )
      {
        var src = document.images[i].getAttribute('src'); // get the src
        var ext = src.substring( src.lastIndexOf('.'), src.length ); // get the file extension
        var hsrc = src.replace( ext, '_r' + ext ); // store the rollover src
        document.images[i].setAttribute('hsrc', hsrc); // set the new src attribute
        document.images[i].style.cursor = 'hand'; // Hand cursor where supported

        // Preload the image
        preLoad[i] = new Image();
        preLoad[i].src = hsrc;

        // Add the rollover functions
        document.images[i].onmouseover = function()
        {
          tempSrc = this.getAttribute('src');
          this.setAttribute('src', this.getAttribute('hsrc'));
        }
        document.images[i].onmouseout = function()
        {
          if (!tempSrc) tempSrc = this.getAttribute('src').replace('_r'+ftype, ftype);
          this.setAttribute('src', tempSrc);
        }
      }
    }
  }
}
function ie6fix()
{
    if ( document.getElementById('panel_list') && isIE6 )
    {
        // Figure out how many columns from the div id
        var cols = 0;
        for ( var h = 2; h < 6; h ++ )
        {
            if ( document.getElementById('panels' + h) )
            {
                cols = h;
            }
        }
        if ( cols )
        {
            // Remove the margin from the left column
            var d = document.getElementById('panels' + cols);
            var ul = d.getElementsByTagName('ul');
            if ( ul.length ){
                for ( var i = 0; i < ul.length; i ++ )
                {
                    if ( i == 0 || ( i / cols ) == Math.round( i / cols ) )
                    {
                        ul[i].style.marginLeft = '0';
                    }
                }
            }
        }
    }
}
function openMenu( divId, ulClass ){
	if ( document.getElementById( divId ) )
	{
		var UL = document.getElementById( divId ).getElementsByTagName('ul'); // Get all the ul's
		for ( var i = 0; i < UL.length; i ++ ) // Go through ul's
		{
			if ( UL[i].className == ulClass ) // Get the main menu
			{
				var LI = UL[i].getElementsByTagName('li'); // Get the li's in the toggle menu
				for ( var j = ( LI.length - 1 ); j >= 0; j -- ) // Go through the li's backwards
				{
					// Check if this line links to this page
					if ( LI[j].firstChild && LI[j].firstChild.href ) // If there's a href
					{
						if ( LI[j].firstChild.href.toLowerCase() == window.location.toString().toLowerCase() ) // Matching the page address window.location
						{
							// Open the list items the element is inside of
							var element = LI[j];
							do {
							    if ( element.tagName.toLowerCase() == 'li' )
							    {
							        element.className = "open"; // Hightlight it
							    }
							    element = element.parentNode;
							} while ( element.className != ulClass )
						}
						
						// Hide the PDF links in the right menu
					    if ( divId == 'col2d' )
					    {
					        // Get the inner text
					        var text = ( LI[j].innerText )? LI[j].innerText : LI[j].textContent;
					        
					        if ( ( text.indexOf('information') != -1 ) && ( text.indexOf('PDF') != -1 ) )
					        {
					            LI[j].style.display = 'none';
    					    }
					    }
					}
				}
			}
		}
	}
}

function cssFixes()
{
    if ( isMac )
    {
        // Dynamically add a new stylesheet to the head for macs
        var cssNode = document.createElement('link');
        cssNode.type = 'text/css';
        cssNode.rel = 'stylesheet';
        cssNode.href = '/schema/stylesheets/mac_';
        cssNode.href += ( isFireFox )?'firefox':'safari';
        cssNode.href += '_v2.css';
        cssNode.media = 'all';
        cssNode.title = 'dynamicLoadedSheet';
        document.getElementsByTagName('head')[0].appendChild(cssNode);
    }   
    // Product Tech spec table css modifications
    // removes the top border on the line below a header2
    if ( document.getElementById('product') )
    {
	    var T = document.getElementById('product').getElementsByTagName('table'); // Get all the tables in column 2
        for ( var i = 0; i < T.length; i ++ )
        {
            if ( T[i].className == 'data' )
            {
                var TR = T[i].getElementsByTagName('tr');
                for ( var j = 0; j < TR.length; j ++ )
                {
                    //debugger;
                    var TD = TR[j].getElementsByTagName('td');
                    var H2 = false;
                    for ( var k = 0; k < TD.length; k ++ )
                    {
                        if ( TD[k].className == 'header2' )
                        {
                            H2 = true;
                            break;
                        }
                    }
                    // If header row found and a row exists below it
                    if ( H2 && TR[j + 1] )
                    {
                        // Add a class to the tr tag and skip the next line in the loop
                        TR[j + 1].className = 'no_border';
                        j ++;
                    }
                }
            }
        }
    }
}

function activePopupLinks()
{
  var A = document.getElementsByTagName('a'); // Get all the links
  for ( var i = 0; i < A.length; i ++ ) // Go through links
  {
    // hide the pdf brochure links
    //if ((A[i].href.indexOf('/generator/index.htm') != -1) || (A[i].href.indexOf('/pdf_brochure/index.htm') != -1)) {
    // A[i].style.display = 'none';
    //}       
    if ( A[i].className.indexOf('popup-') != -1 ) // Find the popups
    {
      var w = A[i].className.split('-')[1].split('x')[0]; // Get the width
      var h = A[i].className.split('-')[1].split('x')[1]; // Get the height
      
      var here   = window.location.href;
      var qrystr = "?referrer="+here;
      
      A[i].href = 'javascript:popup(\'' + A[i].href + qrystr + '\',' + w + ',' + h + ');'; // Rebuild the link      
    } 
  }
}

function popup( win, w, h )
{
  if ( window.pop ){ window.pop.close(); } // close an open one
  pop = window.open( win,'return','toolbar=no,location=no,directories=no,status=yes,scrollbars=yes,resizable=no,copyhistory=no,locationbar=no,width=' + w + ',height=' + h);
}

function xmlhttpPost( urlStr, queryStr, updatePageFunction )
{
	var xmlHttpReq = false;
	var self = this;
	// Figure out the required request type
	if ( window.XMLHttpRequest ) // Mozilla/Safari
	{
		self.xmlHttpReq = new XMLHttpRequest();
	}
	else if ( window.ActiveXObject ) // IE
	{
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	// Build the request.
	self.xmlHttpReq.open('POST', urlStr, true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	
	// Define callback function, with nested function passed to this routine.
	self.xmlHttpReq.onreadystatechange = function()
	{
      if ( self.xmlHttpReq.readyState == 4 )
      {
          updatePageFunction(self.xmlHttpReq.responseText);
      }
	}
	// Send the post request.
	self.xmlHttpReq.send(queryStr);
}

function createPrintFlash()
{
    // If it's a product layout
    if ( document.getElementById('product') )
    {
        // Get the paragraphs
	    var P = document.getElementById('product').getElementsByTagName('p');
        for ( var i = 0; i < P.length; i ++ )
        {
            // If it's the flash one
            if ( P[i].className == 'flash' )
            {
                // Store the paragraph instance globally to be used later
                flashPara = P[i];
                
                // Get the params of the flash inside
                var PARAM = P[i].getElementsByTagName('param');
                for ( var j = 0; j < PARAM.length; j ++ )
                {
                    // If it's the movie param
                    if ( PARAM[j].name == 'movie' )
                    {
                        // Get the src
                        var src = PARAM[j].value;
                        // If it's passing a media location
                        if ( src.indexOf('media_location=') != -1 )
                        {
                            // Get the media location
                            var loc = src.split('media_location=')[1];
                            var query = 'location=' + escape( loc.split('.com')[1] );
                            var action = '/cgi/dmplx_xml_dir/dmplx_xml_directory.cgi';
                            xmlhttpPost( action, query, function( reply ){
						        updatePrintFlash( reply );
					        });
                        }
                    }
                }
            }
        }
    }
}

function updatePrintFlash( reply )
{
    // Extract the first src
    var src = reply.split('src="')[1];
    src = src.split('"')[0];
    
    // Create a new paragraph and image
    var pNode = document.createElement('p');
    pNode.className = 'print_flash';
    var iNode = document.createElement('img');
    iNode.src = src;
    
    // Insert the image in the para and the para into the correct div
    pNode.appendChild(iNode);
    flashPara.parentNode.appendChild(pNode);
}

function insertTitle()
{
    var title = '';
    var found = 0;
    
    // get all the p tags
    var thePs = document.getElementsByTagName('p');
    for (i=0; i<thePs.length; i++) {
        if (thePs[i].className.indexOf('pageheader') != -1) {
            found = 1;
            title = thePs[i].innerHTML;
            thePs[i].style.display = 'none';
        }
    }


    if (!found) {
        // Get the location path 
        var lp = location.pathname.split('/');
    
        var swap = new Array();
        swap[0] = new Array('KITCHENS_BATHROOMS','KITCHENS & BATHROOMS');
        
        if ( lp.length > 4 )
        {
            lp[3] = lp[3].format();
            title = lp[3].toUpperCase();
            if ( lp.length > 3 && lp[4] && (lp[4] != 'index.htm' ) && ( lp[4] != '') )
            {
                if (lp[4].indexOf('.htm') != -1) {
                    lp[4] = lp[4].substr(0,lp[4].indexOf('.htm'));
                }
                lp[4] = lp[4].format();
                title += ' - ' + lp[4].toUpperCase();
            }        
        }
        else if (lp.length > 3) {
            lp[2] = lp[2].format();
            title = lp[2].toUpperCase();
            if ((lp[3] != '') && (lp[3] != 'index.htm')) {
                if (lp[3].indexOf('.htm') != -1) {
                    lp[3] = lp[3].substr(0,lp[3].indexOf('.htm'));
                }
                lp[3] = lp[3].format();
                title += ' - ' + lp[3].toUpperCase();
            }
        }
        else if (lp.length > 2) {
            lp[1] = lp[1].format();
            title = lp[1].toUpperCase();
            if ((lp[2] != '') && (lp[2] != 'index.htm')) {
                if (lp[2].indexOf('.htm') != -1) {
                    lp[2] = lp[2].substr(0,lp[2].indexOf('.htm'));
                }
                lp[2] = lp[2].format();
                title += ' - ' + lp[2].toUpperCase();
            }        
        }
        else if (lp.length > 1) {
            lp[1] = lp[1].format();
            if (lp[1].indexOf('.htm') != -1) {
                lp[1] = lp[1].substr(0,lp[1].indexOf('.htm'));
            }            
            title = lp[1].toUpperCase();
        }
    
        for( var i = 0; i < swap.length; i ++ )
        {
            if ( title == swap[i][0] )
            {
                title = swap[i][1];
            }
        }
        
    
        
        title = title.split('_').join(' ');
    }
        
        //var t = document.createTextNode(title);
        //var p = document.createElement('p');
    var d = document.getElementById('title_bar');
    if (d) {
        var h = d.getElementsByTagName('h1')[0];
        if (h) {
            h.innerHTML = title;
        }
    }
    //p.appendChild(t);
    //d.appendChild(p);
}

var clickmessage="Copyright [c] Dimplex.\nUnauthorised use is forbidden, please contact\nDimplex marketing if you require images.";

function ProtectImages(){
	for(i=0;i<document.images.length;i++) document.images[i].onmousedown=disableclick;
  document.body.oncontextmenu="return false;";
}

function DisableClick(e){
	if (document.all){
		if (event.button==2||event.button==3){
			if (event.srcElement.tagName=="IMG"){
				alert(clickmessage);
			return false;
			}
		}
	} else if (document.layers){
		if (e.which == 3){
			alert(clickmessage);
		return false;
		}
	} else if (document.getElementById){
		if (e.which==3 && e.target.tagName=="IMG"){
			alert(clickmessage);
		return false;
		}
	}
  return false;
}

// Detect when the DOM has loaded
var dom_load = new domFunction(function()
{
    attachEvents(); // Attach javascript events to page elements
    writeCrumbtrail(); // Write to the crumbtrail div
    //emContentImages(); // Convert content images to use em sizing
    ie6fix(); // Handle IE 6 double margin not possible by display:inline
    openMenu('col1','section_menu');
    openMenu('col2d','menu');
    initRollovers();
    cssFixes();
    activePopupLinks();
    createPrintFlash();
    insertTitle();
    if (document.all) document.onmousedown=DisableClick;
    else if (document.getElementById) document.onmouseup=DisableClick;
    else if (document.layers) ProtectImages();
    document.oncontextmenu=new Function("return false;");      
    
}, { 'reg_office' : 'id' }); // Once the last div has been detected
