String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
//debugger;
var params          = [];
var winLoc;
var coverDiv;
var emailForm;
var paramSplit;
var galleryDiv;
var galleryCtl;
var emailStatus;
var loadingImage;
var yourNameInput;
var yourEmailInput;
var sendToFriendDiv;
var friendsNameInput;
var friendsEmailInput;
var yourMessageTextarea;
var customNewsURL = "";
var customNewsHeadline = "";
var customNewsDate = "";

function parseSettings(settings, sep)
{
	//debugger;
    var ret = {};
    var sta = [];
    var stb = [];
    if (!sep)
        sep = "&";
    sta = settings.split(sep);
    for (var i = 0; i < sta.length; i++)
    {
        stb = sta[i].split("=");
        if (stb[0] !== "")
            ret[stb[0].replace(" ", "").toLowerCase()] = stb[1];
    }
    return ret;
}




function cleanPage()
{
	//this used to use __scripts_addLoadEvent but it does not seem to be working, so hacking to make it work for now. fix it when you have time.
	var articleText = document.getElementById("dnn_FooterPane"); //('articleTextId');  
	if(articleText == null){
		setTimeout(cleanPage, 200);
	}else{
		// Remove all non-article elements except the masthead before printing the page.
		var el;

		//if ((el = document.getElementById("dnn_primaryNav")) != null){el.style.display = "none";}
		//if ((el = document.getElementById("dnn_AFLFooter2008")) != null){el.style.display = "none";}
		//if ((el = document.getElementById("dnn_sidebar2008")) != null){el.style.display = "none";}
		//if ((el = document.getElementById("dnn_adLeaderBoard2008")) != null){el.style.display = "none";}
		//if ((el = document.getElementById("bps-wrapper")) != null){el.style.display="none";}
		//if ((el = document.getElementById("bps-footer")) != null){el.style.display="none";}
		if ((el = document.getElementById("bphf-logo")) != null){el.style.display="none";}
		if ((el = document.getElementById("bphf-header")) != null){el.style.display="none";}
		if ((el = document.getElementById("bphf-bottom")) != null) { el.style.display = "none"; }
		//if ((el = document.getElementById("dnn_sorrentoHeader2008")) != null){el.style.display = "none";}
		if ((el = document.getElementById("dnn_ContentPane")) != null) { el.style.width = "95%"; }
		
		if ((el = document.getElementById("dnn_TopPane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_HeaderPane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_LeftPane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_RightPane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_GalleryPane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_SidePane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_AdPane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_FooterPane")) != null){el.style.display="none";}
		if ((el = document.getElementById("dnn_AdminPane")) != null){el.style.display="none";}

		showPrint();
	}
}

function showPrint()
{
    window.focus();
    window.print();
}


function launchPrintWindow()
{
	//window.print();
    printWindow = window.open("http://" +window.location.host+window.location.pathname+(params.print ? "" : window.location.search == "" ? "?print=true" : window.location.search+"&print=true"), "PrintWindow", 'height=800,width=920,top=150,left=150,resizable=yes,menubar=yes,toolbar=yes,scrollbars=yes');
}

function launchCustomPrintWindow(url)
{
	//window.print();
    printWindow = window.open(url + '?print=true', "PrintWindow", 'height=800,width=920,top=150,left=150,resizable=yes,menubar=yes,toolbar=yes,scrollbars=yes');
}

function increaseTextSize(el, selector) {
    if(document.getElementById('htmlBody'))
        el = document.getElementById('htmlBody');

    //debugger;
	if(!el.style.fontSize)
	    el.style.fontSize= "12px";
	
	if(parseInt(el.style.fontSize)+4 > 24)
		el.style.fontSize = "24px";
    else
        el.style.fontSize = (parseInt(el.style.fontSize)+4)+"px";
    for(var x=0; x < el.childNodes.length; x++)
    {
        if(el.childNodes[x].style)
        {
            if(!el.childNodes[x].style.fontSize)
                el.childNodes[x].style.fontSize = "12px";
            el.childNodes[x].style.fontSize = (parseInt(el.childNodes[x].style.fontSize)+4)+"px";
            if(parseInt(el.childNodes[x].style.fontSize)+4 > 24)
                el.childNodes[x].style.fontSize = "24px";
        }
    }
    if(selector)
        window.scrollTo($newsArticle(selector).attr("offsetLeft"), $newsArticle(selector).attr("offsetTop"));
}

function decreaseTextSize(el, selector)
{
    if(document.getElementById('htmlBody'))
        el = document.getElementById('htmlBody');

	if(!el.style.fontSize)
	    el.style.fontSize= "12px";
	if(parseInt(el.style.fontSize)-4 < 12)
		el.style.fontSize = "12px";
	else
        el.style.fontSize = (parseInt(el.style.fontSize)-4)+"px";    	
	
    for(var x=0; x < el.childNodes.length; x++)
    {
        if(el.childNodes[x].style)
        {
            if(!el.childNodes[x].style.fontSize)
                el.childNodes[x].style.fontSize = "12px";
            el.childNodes[x].style.fontSize = (parseInt(el.childNodes[x].style.fontSize)-4)+"px";
            if(parseInt(el.childNodes[x].style.fontSize)-4 < 12)
                el.childNodes[x].style.fontSize = "12px";
        }
    }
    if(selector)
        window.scrollTo($newsArticle(selector).attr("offsetLeft"), $newsArticle(selector).attr("offsetTop"));
}

function defaultTextSize(el)
{
	el.style.fontSize = "12px";
    for(var x=0; x < el.children.length; x++)
    {
        el.childNodes[x].style.fontSize = "12px";
    }

}

function displaySendToFriend(el, position)
{   
    // close all other 'send to friend popups'.
    if (sendToFriendDiv != null)
    {
        sendToFriendDiv.style.display = "none";
    }
    
    
    newsURL = "";
    //debugger;
    var positionStyle;
    if(position == 'top')
      positionStyle = "right:40px; top:80px;";
    else
        positionStyle = "left: 0px; bottom: 22px;";
    
    sendToFriendDiv = new utl.addEl({parent:el, css:positionStyle}, "class", "articleEmail"); sendToFriendDiv.className = "sendToFriend";
    var sendToFriendH2 = new utl.addEl({parent:sendToFriendDiv, text:"Send to a friend", name:"h2"}); sendToFriendH2.className = "sendToFriend";
    var closeBtn = new utl.addEl({parent:sendToFriendH2, name:"a"}, "href", "javascript:;"); closeBtn.className = "closeBtn";
    emailForm = new utl.addEl({parent:sendToFriendDiv, name:"div"}, "class", "emailForm"); emailForm.className = "emailForm";
    var fieldSet1 = new utl.addEl({parent:emailForm, name:"fieldset"});
    var yourNameLabel = new utl.addEl({parent:fieldSet1, name:"label", text:"Your name"}, "for", "yourName");
    yourNameInput = new utl.addEl({parent:fieldSet1, name:"input"}, "id", "yourName", "class", "searchText", "type", "text", "value", "", "name", "yourName");
    var yourEmailLabel = new utl.addEl({parent:fieldSet1, name:"label", text:"Your email"}, "for", "yourEmail");
    yourEmailInput = new utl.addEl({parent:fieldSet1, name:"input"}, "id", "yourEmail", "class", "searchText", "type", "text", "value", "", "name", "yourEmail");
    var fieldSet2 = new utl.addEl({parent:emailForm, name:"fieldset"});
    var friendsNameLabel = new utl.addEl({parent:fieldSet2, name:"label", text:"Friend's name"}, "for", "friendsName");
    friendsNameInput = new utl.addEl({parent:fieldSet2, name:"input"}, "id", "friendsName", "class", "searchText", "type", "text", "value", "", "name", "friendsName");
    var friendsEmailLabel = new utl.addEl({parent:fieldSet2, name:"label", text:"Friend's email"}, "for", "friendsEmail");
    friendsEmailInput = new utl.addEl({parent:fieldSet2, name:"input"}, "id", "friendsEmail", "class", "searchText", "type", "text", "value", "", "name", "friendsEmail");
    
    var acDiv = new utl.addEl({parent:emailForm}); acDiv.className = "actions";
    var formButton = new utl.addEl({parent:acDiv, name:"input"}, "type", "button", "value", "submit"); formButton.value = "Send";
    utl.attachMouseEvents(formButton, mouseHandler);
    coverDiv = new utl.addEl({parent:sendToFriendDiv}); coverDiv.className = "coverDiv";
    emailStatus = new utl.addEl({parent:acDiv, text:" "}); emailStatus.className = "emailStatus";
    loadingImage = new utl.addEl({parent:coverDiv, name:"img"}, "src", "/images/ajax-loader.gif");
    utl.attachMouseEvents(closeBtn, closeHandler);
    
    //var clearDiv = new utl.addEl({parent:el});
}

function setSendToFriendCustomDetails(newsURL, newHeadline, newsDate)
{   
    customNewsURL = newsURL;
    customNewsHeadline = newHeadline;
    customNewsDate = newsDate;
}

function mouseHandler(p, msg)
{
    if(msg == "click")
    {
        sendToFriend(emailForm);
    }
}

function closeHandler(p, msg)
{
    if(msg == "click")
    {
        sendToFriendDiv.style.display = "none";
    }
    if(msg == "enter")
    {
        sendToFriendDiv.style.cursor = "pointer";
    }
    if(msg == "leave")
    {
        sendToFriendDiv.style.cursor = "default";
    }
    return false;
}

function resizeImage(img)
{
	//debugger;
	var ratio;
	var wRatio = 0;
	var hRatio = 0;
	
	if(img.width > 236)
	{
		wRatio = img.width / 236;
	}
	if(img.height > 320)
	{
		hRation = img.height / 320;
	}
	if(wRatio > hRatio)
	{
		img.width = img.width * wRatio;
		img.height = img.height * wRatio;
	} else if(wRatio < hRatio)
	{
		img.width = img.width * hRatio;
		img.height = img.height * hRatio;
	} else if(wRatio == hRatio && wRatio > 0)
	{
		img.width = img.width * wRatio;
		img.height = img.height * hRatio;
	}
	
	
}

function launchLightbox(newsid)
{
	galleryDiv = new utl.addEl({parent:$newsArticle("articleTools"), css:"display:none;"});
    galleryCtl = new utl.photoGallery({parent:galleryDiv, w:32, h:2});
	utl.makeFeedRequest({feed:"NewsGalleryGet",params:{"newsid": newsid},fnc:_setGalleryImages});
}

function _setGalleryImages(results)
{
    if(results)
    {
        if(!(results.row instanceof Array))
        {
            var row = results.row;
            results.row = new Array();
            results.row[0] = row;
        }
        galleryCtl.updateGallery(results.row);
		//debugger;
        galleryCtl.showSlideShow();
        //galleryCtl.slideShowDiv.style.top = "300px";
        //p.data.galleryLoader.hide();
    }
    //else
    //{
    //    galleryCtl.updateGallery(null);
        //p.data.galleryLoader.hide();
    //}
    //galleryCtl.showSlideShow();
    //
    //galleryCtl.slideShowDiv.style.top = "300px";
}


function $newsArticle(el)
{
	return document.getElementById(el);
}


function sendToFriend(el)
{
    //debugger;
    var a = window.location.search.split("newsId");
    if(a[1])
        var b = a[1].split("&");
    var newsId = b ? b[0] : a[1] ? a[1] : "none";
    var newsURL = "";
    var newsHeadline = "";
    var newsDate = "";
    
    if(customNewsURL != "")
    {
        newsURL = customNewsURL;
    }
    else
    {
        newsURL = escape(window.location.protocol + "//" + window.location.host + window.location.pathname +"?newsId=") + escape(newsId);
    }
    
    if(customNewsHeadline != "")
    {
        newsHeadline = customNewsHeadline;
    }
    else
    {
        newsHeadline = escape(document.getElementById('articleHeadline').innerHTML);
    }
    
    if(customNewsDate != "")
    {
        newsDate = customNewsDate;
    }
    else
    {
        newsDate = escape(document.getElementById('articleDate').innerHTML);
    }
    
    emailStatus.innerHTML = "Sending email";
    coverDiv.style.display = "block";
    var params = "uname=" + escape(yourNameInput.value) + "&uemail=" + escape(yourEmailInput.value) + "&fname=" + escape(friendsNameInput.value) + "&femail=" + escape(friendsEmailInput.value) + "&newsURL=" + newsURL + "&headline=" + newsHeadline + "&date=" + newsDate;
    utl.makePost("/newssendtofriend.aspx", params, function(responseText, status) { sendEmailComplete(responseText, status); });
    //setTimeout("sendComplete("+responseText+", "+status+"", 5000);
}

function sendEmailComplete(responseText, status)
{
    //debugger;
    coverDiv.style.display = "none";
    if(status == 200)
    {
        emailStatus.innerHTML = "Email sent, thank you";
        yourNameInput.value = "";
        yourEmailInput.value = "";
        friendsNameInput.value = "";
        friendsEmailInput.value = "";
    }
    else if(status !== undefined)
        emailStatus.innerHTML = "Error sending email, try again later";
}


//utl.addStyles(g_lightboxStyles);

//ani.start();

if (utl == undefined) 
  var utl = {};
if (g_addElDef == undefined)
  var g_addElDef = { parent : document.body, name : "div", style : null, text : null, css : null, fncMouse : null, x : null, y : null, w : null, h : null, z : null, position:null, bgx : null, bg : null, className : null};
if (utl.addEl == undefined)
  utl.addEl = function() {
      var args = utl.findArgs(g_addElDef);
      var el = document.createElement(args.name);
      
      if (args.vargs)
      {
          for(var i = 0; i < args.vargs.length; i+=2)
              el[args.vargs[i]] = args.vargs[i+1];
      }
      
      if (args.css !== null)
          el.style.cssText = args.css;
          
      if (args.style !== null)
          utl.setElementStyle(el, args.style);
      
      if (args.text !== null)
          el.innerHTML = args.text;
          
          
      if ((args.x !== null || args.y !== null) && args.position ===null)
          el.style.position = "absolute";
      if (args.position !== null)
          el.style.position = args.position;
      if (args.x !== null)
          el.style.left = args.x + "px";
      if (args.y !== null)
          el.style.top = args.y + "px";
      if (args.z !== null)
          el.style.zIndex = args.z;
          
      if (args.fncMouse)
          utl.attachMouseEvents(el, args.fncMouse);

      if (args.w !== null)
      {
          // Adjust for box model
          el.style.width = utl.calcActualWidth(el, args.w) + "px";
      }
      if (args.h !== null)
      {
          // Adjust for box model
          el.style.height = utl.calcActualHeight(el, args.h) + "px";
      }
          
      if (args.bgx !== null)
          utl.setBgImage(el, args.bgx, "repeat-x");
      if (args.bg !== null)
          utl.setBgImage(el, args.bg);

      if (args.parent)
          args.parent.appendChild(el);
      else
          document.body.appendChild(el);
          
      if(args.className !== null)
          el.className = args.className;
          
      return el;
  };
if (utl.findArgs == undefined)
  utl.findArgs = function(def) {
      var out = {};
      
      var args = fIE ? arguments.caller : utl.findArgs.caller.arguments;
      
      for(var i in def)
      {
          if (args.length === 0 || !(i in args[0]))
              out[i] = def[i];
          else
              out[i] = args[0][i];
      }
      
      
      // Handle variable args (anything past argument 0)
      if (args.length > 1)
      {
          out.vargs = [];
      
        for(i=1; i < args.length; i++)
              out.vargs[i-1] = args[i];
      }
      
     return out;
  };
if (utl.setElementStyle == undefined)
  utl.setElementStyle = function(el, strStyle) {
    var str = strStyle === undefined ? el.nodeName : strStyle;
    
    var s = g_stylesParsed[str];
    
    if (!s)
    {
        
        s = [];
        
        var strStyleText = utl.getStyle(str);
        
        // Parse out style so that we can merge it in
        if (strStyleText)
        {
            var a = strStyleText.split(";");
            var iStyle = 0;
            for(var i=0; i < a.length; i++)
            {
                var aa = a[i].split(":");
                
                if (aa.length > 1)
                {
                    var strName = aa[0].trim();
                    var strMapped = g_cssNameMap[strName];
                    var strVal = a[i].substr(a[i].indexOf(":")+1).trim();
                        
                    s[iStyle++] = { name : strMapped ? strMapped : strName, value : strVal };
                }
            }
        }
        
        g_stylesParsed[str] = s;
    }
    
    for(i=0; i < s.length; i++)
    {
      try {
        el.style[s[i].name] = s[i].value;
      }
      catch (Exception) {
          if (!g_prod)
          {
            alert("Invalid CSS Value\nProperty: " + s[i].name + "\nValue: " + s[i].value);
        }
      }
    }
  };
if (utl.attachMouseEvents == undefined)
  utl.attachMouseEvents = function(el, fnc, fReceiveCoords, fCoordsRelative) {

      var closure = { el : el, fnc : fnc, fCoords : fReceiveCoords, fRelative : fCoordsRelative};
      
      function getCoordsOnPage(e)
      {
          var evt = e || event;
        if (evt.pageX || evt.pageY)
            return { x : evt.pageX, y : evt.pageY };
        else if (evt.clientX || evt.clientY)
            return { x : evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft, y : evt.clientY + document.body.scrollTop + document.documentElement.scrollTop };
      }
      
      function getCoords(e)
      {
          var evt = e || event;
          
          var x = evt.offsetX;
          var y = evt.offsetY;
          
          var elCheck = fIE ? evt.srcElement : evt.target;
          
          for(; elCheck !== closure.el; elCheck=elCheck.parentNode)
          {
              x += elCheck.offsetLeft;
              y += elCheck.offsetTop;
          }
          
           
          return { x : x, y : y };
      }
      
      function callHandler(e, msg)
      {

          if (closure.fCoords)
              closure.fnc(closure.el, msg, closure.fRelative ? getCoords(e) : getCoordsOnPage(e));
          else
              closure.fnc(closure.el, msg);
      }
      function handleClick(e)
      {
          callHandler(e, "click");
      }
      function handleEnter(e)
      {
          callHandler(e, "enter");
      }
      function handleLeave(e)
      {
          callHandler(e, "leave");
      }
      function handleMove(e)
      {
          callHandler(e, "move");
      }
    
      utl.attachEvent(el, "onclick", handleClick);
      utl.attachEvent(el, "onmouseover", handleEnter);
      utl.attachEvent(el, "onmouseout", handleLeave);
      utl.attachEvent(el, "onmousemove", handleMove);
  };
if (g_eventhandlers == undefined) 
  var g_eventhandlers = [];
  
if (utl.attachEvent == undefined) 
utl.attachEvent = function(el, msg, fnc) {
    g_eventhandlers.push( {el : el, msg : msg, fnc : fnc} );
    
    if (fIE)
        el.attachEvent(msg, fnc);
    else
    {
        // Remove 'on'
        el.addEventListener(msg.substr(2), fnc, false);
    }
};

if (utl.makeRequest == undefined) 
utl.makeRequest = function(strURL, fnc) {
    //debugger;
    var xmlHttpReq = false;
    var fncCB = fnc;
    var strURLCB = strURL;
    
    // Mozilla/Safari
    if (window.XMLHttpRequest)
    {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
    {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttpReq.open('GET', strURL, true);
    
    function stateHandler()
    {
        if (xmlHttpReq.readyState == 4)
        {
//            xmlHttpReq.onreadystatechange = null;
            fncCB(xmlHttpReq.responseText, strURLCB, xmlHttpReq.status);
        }
    }
        
    xmlHttpReq.onreadystatechange = stateHandler;
    
    xmlHttpReq.send(null);
};
if (utl.makePost == undefined) 
utl.makePost = function(strURL, params, fnc) {
    var xmlHttpReq = false;
    var fncCB = fnc;
    var strURLCB = strURL;
    
    // Mozilla/Safari
    if (window.XMLHttpRequest)
    {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
    {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttpReq.open('POST', strURL, true);
    
    xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttpReq.setRequestHeader("Content-length", params.length);
    xmlHttpReq.setRequestHeader("Connection", "close");
    
    xmlHttpReq.onreadystatechange = function()
    {
        if (xmlHttpReq.readyState == 4)
        {
            //xmlHttpReq.onreadystatechange = null;
            fncCB(xmlHttpReq.responseText, xmlHttpReq.status);
        }
    };
    
    xmlHttpReq.send(params);
};
if (utl.findFunc == undefined) 
utl.findFunc = function(strFunc) {
    var fnc;
    try
    {
        fnc = eval(strFunc);
    }
    catch(e) {}
    
    return fnc;
};



if (window.location.search) 
{
	params = parseSettings(window.location.search.split("?")[1], "&");
	if (params.print){
		//var docBody = document.body;
		//docBody.setAttribute('onload','alert(\'new\');');
	    //__scripts_addLoadEvent(cleanPage);
		cleanPage();
	}
}
