// JavaScript Document

// See the description of
// clsStringFunctions.DecodeGet
// If you change this method, change DecodeGet as well.
function escape2(s) 
{
    return(escape(s.replace(/&/g, '====')));
}

function returnPressed(e)
{
    var keynum;
    if(window.event) // IE
      {
      keynum = e.keyCode;
      }
    else if(e.which) // Netscape/Firefox/Opera
      {
      keynum = e.which;
      }

    return(keynum==13);
}

function toggle(i)
{
  obj=document.getElementById(i); 
  if (obj.style.display == 'none'){	  
	obj.style.display = 'block'	
  }else{ 	
	obj.style.display = 'none'  
  }
}

function toggleContainer(container, clickmarker, trackPageUrl, originId, Id)
{
  obj=document.getElementById(container); 
  
  if (obj.style.display == 'none') {
      document.getElementById(clickmarker).innerHTML =
        '<img src="' + trackPageUrl + '?Origin=' + originId +
        '&ID=' + Id + '&misc=' + new Date().getTime() +
        '" width="1" height="1" />';
        
	  obj.style.display = 'block';
  }else{ 	
  	obj.style.display = 'none'; 
  }
}

function closeContainer(container)
{
    document.getElementById(container).style.display = 'none'; 
}

//function changeText(a)
//{
//  if (a.firstChild.nodeValue == 'View all'){	  
//	a.firstChild.nodeValue = 'Collapse'	
//  }else{ 	
//	a.firstChild.nodeValue = 'View all' 
//  }
//}

function clearText(thefield)
{
    if (thefield.defaultValue==thefield.value)
        thefield.value = ''
}

function clearText2(thefield, defaulttext)
{
    if (defaulttext==thefield.value)
        thefield.value = ''
}

function checkText(thefield)
{
    if (thefield.value=='')
        thefield.value = thefield.defaultValue
}

function checkText2(thefield, defaulttext)
{
    if (thefield.value=='')
        thefield.value = defaulttext
}

//function ValidateEnewsQuickRego(emailaddressfield)
//{
//	if (isEmailAddress(emailaddressfield.value))
//	{
//	    return true;
//	}
//	else
//	{
//	   alert('You must enter a valid email address');
//		emailaddressfield.focus();
//		return false;
//	}
//}

function isEmailAddress(sIn) 
{
	return (sIn.search(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/) > -1)
}

function openPopup(url, w, h)
{
	var win = window.open(url,"_blank", "status=yes,toolbar=no,width="+w+",height="+h);
	
	// if popup blocker stops win from being created
	if (win != null)
	{
	    win.opener = window;
	    win.focus();
	}
}

function openRepeatVisitorPopup()
{
  openPopup("PopupRepeatVisitor.aspx", 400, 400)
}

function changeParentLocationURL(url)
{
	var current = escape(window.opener.location.href);

	var from = "f=" + current; // f= used to be from=

	if (url.lastIndexOf("?") < 0)
		from = "?" + from;
	else
		from = "&" + from;

	window.opener.location.href = url + from;
	window.close();
}


function ClickthroughRedirect(url)
{
    window.open(url + "&rid=" + getRandomID());
    return false;
}

function CopyElement(eSourceName,eDestName)
{
    var e1=document.getElementById(eSourceName);
    if (e1 != null)
    {
        var e2=document.getElementById(eDestName);
        if (e2 != null)
        {
            e2.innerHTML=e1.innerHTML;
        }
    }
}

// --- Google ads
// See Google documentation for Javascript AFC ads

// Code to set this variable gets generated by clsAdProviderGoogleAFCJavaScript
var adIdPrefix = '';

// Because we never show image or flash ads, all code that deals with image and flash ads
// has been removed from this function.
function google_ad_request_done(google_ads) 
{
    var i;
    for(i=0; i < google_ads.length; ++i) 
    {
        var adid=adIdPrefix+((i+1).toString());	
        var ad=document.getElementById(adid);

        if (ad != null)
        {
            var adHeader='';
            var adClass=ad.className;

            if ((adClass=='InsertNarrowHeader') || (adClass=='InsertWideHeader'))
            {
	              var headerFloat='';
	              if (adClass=='InsertWideHeader')
	              {
		              headerFloat=' style="float: right;"';
		          }
		          else 
	              {
	                  headerFloat = ' style="text-align: right;"';
	              }

                  var feedbackurl = google_info.feedback_url;
                  var useFeedback = (use_feedback == 'on') && (feedbackurl != null) && (feedbackurl != '');

	              adHeader = '<div class="toptitle"' + headerFloat + '>';
	              if (useFeedback) {
	                  adHeader += '<a target=\"_blank\" href="' + feedbackurl + '">';
	              }
	              adHeader += afc_ad_box_header;
	              if (useFeedback) {
	                  adHeader += '</a>';
	              }
	              adHeader += '</div>';
            }

            var s = 
		            '<div class="SingleHorizontal">' +
		            adHeader +
		            '<div class="Heading">' +
		            '<a target=\"_blank\" href="' + google_ads[i].url + '">' +
                        google_ads[i].line1 +
		            '</a>' +
		            '</div>' +
		            '<div class="BodyText">' +
                google_ads[i].line2;

	          if (google_ads[i].line3 != '')
	          {
           	    s += ' ' + google_ads[i].line3;
	          }

    		    s +=
		            '</div>' +
		            '<div class="Footer">' +
		            '<a target=\"_blank\" href="' + google_ads[i].url + '">' +
                        google_ads[i].visible_url +
		            '</a>' +
		            '</div>' +
		            '</div>';

            ad.innerHTML=s;
        }
    }
}

function getRandomID() {
  var Now = new Date;
  return Now.getMilliseconds() + "-" + (((1+Math.random())*0x10000)|0).toString(16).substring(1)
}

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

//  strings

// Removes leading whitespaces
function LTrim(value) {

    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim(value) {

    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trim(value) {

    return LTrim(RTrim(value));

}


// css stuff

function containsCssClass(e, strClassName) {
    var a = ' ' + e.className + ' ';
    var b = a.indexOf(' ' + strClassName + ' ');
    return (b >= 0);
}

function addCssClass(e, strClassName) {
    if (!containsCssClass(e, strClassName)) {
        if (e.className == '') {
            e.className = strClassName;
        }
        else {
            e.className += ' ' + strClassName;
        }
    }
}

function removeCssClass(e, strClassName) {
    var a = ' ' + e.className + ' ';
    var b = a.indexOf(' ' + strClassName + ' ');

    if (b >= 0) {
        e.className =
            trim(a.substring(0, b) + ' ' + a.substring(b + strClassName.length + 1, a.length));
    } 
}

// element stuff

function getLocation(e) {
    var b = 0;
    var c = 0;
    var a;

    for (a = e; a; a = a.offsetParent) {
        if (a.offsetLeft) { b += a.offsetLeft; }
        if (a.offsetTop) { c += a.offsetTop; }
    }

    return { x: b, y: c }
}

function setLocation(e, x, y)
{
    var a = e.style;
    a.position='absolute';
    a.left=x+'px';
    a.top=y+'px';
}

// ---- cookie stuff

function createCookie(name, value, days) 
{
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = "; expires="+date.toGMTString();
  }

  document.cookie = name+"="+value+expires+"; path=/"; 
}

function readCookie(name)
{
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return null;
}

function eraseCookie(name)
{
  createCookie(name, "", -1);
}

function SetOpacity(elem, opacityAsInt) {
    var opacityAsDecimal = opacityAsInt;

    if (opacityAsInt > 100)
        opacityAsInt = opacityAsDecimal = 100;
    else if (opacityAsInt < 0)
        opacityAsInt = opacityAsDecimal = 0;

    opacityAsDecimal /= 100;
    if (opacityAsInt < 1)
        opacityAsInt = 1; // IE7 bug, text smoothing cuts out if 0

    elem.style.opacity = (opacityAsDecimal);

    // for ie
    elem.style.filter = "alpha(opacity=" + opacityAsInt + ")";
    elem.style.zoom = 1;
}

function FadeOpacity(elemId1, elemId2, fromOpacity, toOpacity, time, fps) {
    var steps = Math.ceil(fps * (time / 1000));
    var delta = (toOpacity - fromOpacity) / steps;

    FadeOpacityStep(elemId1, elemId2, 0, steps, fromOpacity,
                    delta, (time / steps));
}
function FadeOpacityStep(elemId1, elemId2, stepNum, steps, fromOpacity,
                         delta, timePerStep) {
    var e1 = document.getElementById(elemId1);
    var e2 = document.getElementById(elemId2);

    SetOpacity(
        e1,
        Math.round(parseInt(fromOpacity) + (delta * (steps - stepNum))));

    SetOpacity(
        e2,
        Math.round(parseInt(fromOpacity) + (delta * stepNum)));

    e2.style.visibility = 'visible';

    if (stepNum < steps) {
        e1.style.visibility = 'visible';
        setTimeout(
            "FadeOpacityStep('" +
            elemId1 + "', '" +
            elemId2 + "', " +
            (stepNum + 1) + ", " +
            steps + ", " +
            fromOpacity + ", " +
            delta + ", " +
            timePerStep + ");", timePerStep);
    }
    else {
        e1.style.visibility = 'hidden';
    }
}

function findAbolutePos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
            // code below combines assignment with test on whether
            // parent available
        } while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}


function divArrayFade(arrayId, timeBetweenFades, timeFade, fpsFade) {
    var elemArray = document.getElementById(arrayId);
    var elemsArray = elemArray.getElementsByTagName("div");
    var eVisible;
    var eNext;
    var eVisibleFound = false;
    var eNextFound = false;

    for (i = 0; i < elemsArray.length; i++) {
        var e = elemsArray.item(i)
        if (e.parentNode == elemArray) {
            if (!eVisibleFound) {
                if (e.style.visibility == 'visible') {
                    eVisibleFound = true;
                    eVisible = e;
                }
            }
            else {
                eNextFound = true;
                eNext = e;
                break;
            }
        }
    }

    if (!eVisibleFound) {
        return;
    }

    if (!eNextFound) {
        eNext = elemsArray.item(0);
    }

    // ------

    FadeOpacity(eVisible.id, eNext.id, 1, 100, timeFade, fpsFade)

    setTimeout(
        "divArrayFade('" +
        arrayId + "'," +
        timeBetweenFades + "," +
        timeFade + "," +
        fpsFade + ");", timeBetweenFades + timeFade);
}

// Use this function with a div containing a series of sub-divs, like so:
// <div id="container">
//    <div id="i1">.....</div>
//    <div id="i2">.....</div>
//    <div id="i3">.....</div>
// </div>
//
// Each sub div must have an id.
//
// After you've called the function, each sub div will be faded in,
// kept visible, and then faded out while the next sub div fades in.
//
// arrayId - id of the containing div
// timeBetweenFades - time in milliseconds that a sub div is visible
// timeFade - time in ms taken to fade out/in a sub div
// fpsFade - number of frames per second used by the fade in/out animation. 30 is a good value.
//
function startDivArrayFader(arrayId, timeBetweenFades, timeFade, fpsFade) {
    var elemArray = document.getElementById(arrayId);
    var elemsArray = elemArray.getElementsByTagName("div");

    for (i = 0; i < elemsArray.length; i++) {
        var e = elemsArray.item(i)
        if (e.parentNode == elemArray) {
            var absPos = findAbolutePos(e);
            var absPos0;
            var h0 = 0;
            var e0;
            if (i == 0) {
                absPos0 = absPos;
                e0 = e;
                e.style.visibility = 'visible';
            }
            else {
                e.style.position = 'relative'; //
                e.style.top = (absPos0[1] - absPos[1]) + 'px'; //
                e.style.visibility = 'hidden';

                if (e.offsetHeight > e0.offsetHeight) {
                    e0.style.height = e.offsetHeight + "px";
                }

                SetOpacity(e, 0);
            }

        }
    }

    elemArray.style.height = (e0.offsetHeight + 5) + "px";  //
    elemArray.style.overflow = 'hidden';   //

    setTimeout(
        "divArrayFade('" +
        arrayId + "'," +
        timeBetweenFades + "," +
        timeFade + "," +
        fpsFade + ");", timeBetweenFades);
}

//
// Contact box related
//

function clickCancel(elmntCancel) {
    var elmntBox = document.getElementById("container");
    elmntBox.style.position = 'static';
    elmntBox.style.width = 'auto';
    elmntBox.style.zIndex = '1';
    elmntBox.style.display = m_NormalDisplay;

    removeCssClass(elmntBox, 'movable');

    removeCssClass(document.getElementById("dvContactForm"), 'extend');

    $('#shadeTop').addClass('noshade').removeClass('shade')
    $('#shadeLeft').addClass('noshade').removeClass('shade')
    $('#shadeRight').addClass('noshade').removeClass('shade')
    $('#shadeBottom').addClass('noshade').removeClass('shade')

    $('.dvCompanyLinks').show();

    var elmntMoveBox = document.getElementById("dvContactFormTitleBar");
    elmntMoveBox.onmousedown = null;

    var elmntCancelLink = document.getElementById("lnkCancel");
    elmntCancelLink.style.display = 'none';

    var elmntIFrameContactForm = document.getElementById("ifContactForm");
    elmntIFrameContactForm.style.display = 'none';
}

// ---------

// elmntButton - button that was clicked to float the contact form
// iItemID - WebsiteCustomerID, ShowcaseID of the item
// iOrigin - identifies what sort of item it was for which
//           the button was clicked. For values, see enumOrigin.
// strCustomerName - name of the customer to which the message will be sent.
//

function clickFloatContactBox(
		elmntButton,
		iItemId,
		iOrigin,
		strCustomerName,
		strDelaconNo,
		strRelatedCustomers) {

    var strBoxCaption = m_contactform_BoxCaption;
    strBoxCaption = strBoxCaption.replace(/\{0\}/, strCustomerName);

    initBox2(strBoxCaption, strDelaconNo, strRelatedCustomers, iItemId, iOrigin);

    var iHeightButton = elmntButton.offsetHeight;
    var iWidthButton = elmntButton.offsetWidth;
    var elmntItemId = document.getElementById(m_hdnItemId_ClientID)
    elmntItemId.value = iItemId

    var elmntOrigin = document.getElementById(m_hdnOrigin_ClientID)
    elmntOrigin.value = iOrigin

    // Show the contact form
    document.getElementById("dvContactForm").style.display = 'block';

    var elmntBox = document.getElementById("container");
    elmntBox.style.zIndex = '500';
    elmntBox.style.display = 'block';
    elmntBox.style.position = 'absolute';

    addCssClass(elmntBox, 'movable');

    $('#shadeTop').addClass('shade').removeClass('noshade')
    $('#shadeLeft').addClass('shade').removeClass('noshade')
    $('#shadeRight').addClass('shade').removeClass('noshade')
    $('#shadeBottom').addClass('shade').removeClass('noshade')

    $('.dvCompanyLinks').hide();
    
    if (strRelatedCustomers != '') {
        addCssClass(document.getElementById("dvContactForm"), 'extend');
    }
    else {
        document.getElementById("divRight").style.display = 'none';
    }

    var boxWidth = document.getElementById('dvContactForm').offsetWidth;
    var boxHeight = document.getElementById('dvContactForm').offsetHeight;
    
    var elmntCancelLink = document.getElementById("lnkCancel");
    elmntCancelLink.style.display = 'block';

    var elmntMoveBox = document.getElementById("dvContactFormTitleBar");
    elmntMoveBox.onmousedown = mousedowncb;

    var locBoxOld = getLocation(elmntBox);
    var oldBoxX = locBoxOld.x;
    var oldBoxY = locBoxOld.y;


    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    var scrollLeft = $(window).scrollLeft();
    var scrollTop = $(window).scrollTop();
    
    var newBoxX = ((windowWidth - boxWidth) / 2) + scrollLeft;
    newBoxX = newBoxX > 0 ? newBoxX : 0;

    var newBoxY = ((windowHeight - boxHeight) / 2) + scrollTop;
    newBoxY = newBoxY > 0 ? newBoxY : 0;     

    var increments = 20;
    var period = 300;

    var x = 0;
    var y = 0;
    var delay = 0;

    var t = 0;

    for (var i = 1; i <= increments; i++) {
        x = oldBoxX + Math.round(((newBoxX - oldBoxX) * i) / increments);
        y = oldBoxY + Math.round(((newBoxY - oldBoxY) * i) / increments);
        delay = Math.round((period * i) / increments);

        t = setTimeout('setLocation(document.getElementById("container"), ' + x.toString() + ',' + y.toString() + ')', delay);
    }

    // After the box has stopped moving, make iframe visible under the current position of the contact box.
    var t = setTimeout(
		    'e = document.getElementById("ifContactForm");' +
		    'e.style.display = "block";' +
		    'setLocation(e, ' + (x).toString() + ',' + (y).toString() + ');' +
            'e.style.height=' + (boxHeight).toString() + ';' +
            'e.style.width=' + (boxWidth).toString() + ';',
		    delay);

    return false;
}

// ---------------------

function initBox(
		strBoxHeader,
		strDelaconNo,
		strRelatedCustomers) 
{
    initBox2(strBoxHeader, strDelaconNo, strRelatedCustomers, 0, 0);
}

function initBox2(
		strBoxHeader,
		strDelaconNo,
		strRelatedCustomers,
		iItemID,
		iOrigin) 
{
    var elmntBoxHeader = document.getElementById(m_lblBoxHeader_ClientID);

    // When you assign the strBoxHeader to elmntBoxHeader.innerHTML,
    // IE7 spontaneously increases the margin on top of the contact box.
    // To make this less likely, only change it when it needs to be changed.

    if (elmntBoxHeader.innerHTML != strBoxHeader) {
        elmntBoxHeader.innerHTML = strBoxHeader;
    }

//    var elmntDelacon = document.getElementById(_delacon_ClientID);
//    var elmntLeftColumnHeader = document.getElementById(_leftColumnHeader_ClientID);

//    if (elmntDelacon.innerHTML != strDelaconNo) {
//        elmntDelacon.innerHTML = strDelaconNo;
//    }

//    if (strDelaconNo == '') {
//        elmntLeftColumnHeader.style.display = 'none';
//        elmntDelacon.style.display = 'none';
//    }
//    else {
//        elmntLeftColumnHeader.style.display = 'block';
//        elmntDelacon.style.display = 'block';
//    }

    // ----

    if (strRelatedCustomers == '') {
        var dv = document.getElementById('RelatedCustomers');
        dv.innerHTML = '';

        if ((_showrelatedonall == '1') && (iItemID != 0)) {
            $.get('/Get_RelatedCustomers.ashx', { 'wcid': iItemID, 'o': iOrigin }, function(data) { RelatedCustomersLoaded(data); });
        }

        return; 
    }

    RelatedCustomersLoaded(strRelatedCustomers);
}

function RelatedCustomersLoaded(strRelatedCustomers) 
{
    var arrdefs = strRelatedCustomers.split("___");
    var arrdefslen = arrdefs.length

    var dvcontent = '<fieldset class=fieldset>' +
			'<legend class=labelBold>' + m_contactform_SimilarCompaniesHeader + '</legend><br/>' +
			'<table cellpadding="0" cellspacing="0" class="">';
			
    for (i = 0; i < arrdefslen; i++) {
        var arrdef = arrdefs[i].split("#");
        var customername = arrdef[0].replace(/</gi, "&lt;"); // escape for html
        var websitecustomerid = arrdef[1];

        dvcontent +=
				'<tr><td valign="top"><input type="checkbox" name="' + m_strRelatedCompanyCheckboxPrefix +
				websitecustomerid +
				'" value="1" /></td><td class="label" style="text-align: left" >' +
				customername +
				'</td></tr>'
    }

    dvcontent += '</table>';
    dvcontent += '</fieldset>';

    var dv = document.getElementById('RelatedCustomers');
    dv.innerHTML = dvcontent;
}

// ----------------------

function mousedowncb(event) {
    event = event || window.event;
    document.oldClientX = event.clientX;
    document.oldClientY = event.clientY;
    document.onmousemove = mousemovecb;
    document.onmouseup = mouseupcb;
    return false;
}

function mouseupcb(event) {
    event = event || window.event;
    document.onmousemove = null;
    document.onmouseup = null;
    return false;
}

function mousemovecb(event) {
    event = event || window.event;
    var deltaClientX = event.clientX - document.oldClientX;
    var deltaClientY = event.clientY - document.oldClientY;
    var sender = document.getElementById("container");
    var senderLocation = getLocation(sender);

    var newX = senderLocation.x + deltaClientX;
    var newY = senderLocation.y + deltaClientY;
    setLocation(sender, newX, newY);

    var e = document.getElementById("ifContactForm");
    setLocation(e, newX, newY);
    
    document.oldClientX = event.clientX;
    document.oldClientY = event.clientY;
    return false;
}

// -----------

function contactkeypressed(event) {
    if (returnPressed(event)) {
        $('#' + _btnStartCaptchaCheck_ClientID).click();
        return false;
    };

    return true;
}


