//globals:
_ieLastTextSize="100%";

//------------------------------
function identifyUser() {}     // Obsolete - CA

//------------------------------
function subscribeFeedburner()
{
  var l=location.href;
  var uri="StockChartscom-";
  if (/\/chipanderson(\/|$)/i.test(l)) uri+="ChipAnderson";
  else if (/\/dont_ignore_this_chart(\/|$)/i.test(l)) uri+="DontIgnoreTheChart";
  else if (/\/chartwatchers(\/|$)/i.test(l)) uri+="ChartWatchers";
  else if (/\/mailbag(\/|$)/i.test(l)) uri+="Mailbag";
  else if (/\/scanning(\/|$)/i.test(l)) uri+="ScanningStocks"; 
  else if (/\/status(\/|$)/i.test(l)) uri+="Status";
  else if (/\/step_by_step(\/|$)/i.test(l)) uri+="Step-by-step";
  else if (/\/whats_new(\/|$)/i.test(l)) uri+="WhatsNew";
  else if (/\/canada(\/|$)/i.test(l)) uri+="TheCanadianTechnician";
  else return false;
  location.href="http://feedburner.google.com/fb/a/mailverify?uri="+uri+"&amp;loc=en_US";
}
//------------------------------
function activateChangeTextSize() {
  try{  
    var check=$("body:first");
    if (check.hasClass('scc-sc2')) return;
    if ($("#scc-font-toggle").length==0){
      var base=$("#beta-inner");
      if (base.length==0) base=$("#alpha-inner");
      if (base.length>0 && !check.hasClass('scc-mmadmin')) {
        base.prepend('<div id="scc-font-toggle" class="scc-font-toggle hidden"></div>');
      }
    }
    $("#scc-font-toggle").removeClass("hidden"); 
    $("#scc-font-toggle").append("<span>Font&nbsp;Size:</span>&nbsp;"+
        "<a href=\"#\" onclick=\"changeTextSize(-1);return false;\">&nbsp;-&nbsp;</a>&nbsp;"+
        "<a href=\"#\" onclick=\"changeTextSize(1);return false;\">&nbsp;+&nbsp;</a>&nbsp;"+
        "<a href=\"#\" onclick=\"changeTextSize('reset');return false;\">reset</a>");
    //existing preference:
    var match=(document.cookie+"").match(/sccPrefs=([^\;]+)/);
    if (match) {
       var oldPrefs=decodeURIComponent(match[1]);
       match=(oldPrefs).match(/(^|\|)font=(\-?[\d]+)\|/);
       if (match){
         var fontSize=parseInt(match[2]);
         var isNegative=(fontSize<0);
         for (var i=0;i<Math.abs(fontSize);i++){
           changeTextSize(isNegative?-1:1,false);
         }
       }
    }  
  }catch(e){}
}
//------------------------------
function changeTextSize(changeSize,setCookie){
  if (typeof(setCookie)=="undefined") setCookie=true;
  var parent=$("#alpha");
  var base=$("#alpha-inner");
  if (!base) return;
  if (changeSize=="reset")  {
    base.css("font-size","");
  }
  else{
    changeSize=parseInt(changeSize);
    var parentSize=parent.css("font-size");
    var currentSize=base.css("font-size");
    if (parentSize==currentSize) currentSize="100%";
    if ( currentSize=="") currentSize="100%";
    if (/^[\d\.]+(em|px)$/.test(parentSize) && /^[\d\.]+(em|px)$/.test(currentSize) 
        && parentSize.substr(-2)==currentSize.substr(-2)) {
      var temp=100*(parseFloat(currentSize)/parseFloat(parentSize));
      if (temp && !isNaN(temp)) currentSize=temp+"%";
    }
    if (!/^[\d\.]+\%$/.test(currentSize)) currentSize=_ieLastTextSize;
    if ((currentSize=="300%" && changeSize>0) || (currentSize=="30%" && changeSize<0)) return;
    var nextTextSize=parseInt(currentSize)+((changeSize>0)?10:-10)+"%";
    base.css("font-size", nextTextSize);
    _ieLastTextSize=nextTextSize;
  }
  //save preference:
  if (setCookie){
    var oldPrefs="";
    var fontSize=(changeSize=="reset")?"":changeSize;
    var match=(document.cookie+"").match(/sccPrefs=([^\;]+)/);
    if (fontSize && match) {
      oldPrefs=decodeURIComponent(match[1]);
      match=(oldPrefs).match(/(^|\|)font=(\-?[\d]+)\|/);
      if (match){
         fontSize=parseInt(match[2]);
         fontSize+=changeSize;
      }
    }
    document.cookie="sccPrefs=;expires=Thu, 01-Jan-1970 00:00:01 GMT;path=/";//delete old domain
    oldPrefs="font="+fontSize+"|"+oldPrefs.replace(/font=[^\|]*\|/ig,"");
    var expires = new Date((new Date()).getFullYear()+5, 1, 1);
    document.cookie="sccPrefs="+encodeURIComponent(oldPrefs)+";expires="+expires.toGMTString()+";path=/;domain=.stockcharts.com";//new domain
  }
}
//------------------------------
function breakFrames()
{
  if (typeof(self) == "undefined" || typeof(top) == "undefined") return;
  if (self==top) return; //no frames found
  try{  $("a").attr("target","_top");  }catch(e){}
}
//------------------------------
function addAnalytics() {
  return;  //Remove from most pages - CA
  if (/\/h\-sc\/ui/i.test(location.href)) return;//don't run on sharpcharts, too slow
  _gaq = (typeof(_gaq)!="undefined" && _gaq)?_gaq:[]; //global
  _gaq.push(['_setAccount', 'UA-518575-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var b=document.getElementsByTagName('body');
    if (b) b[0].appendChild(ga);
  })();
}
//------------------------------
function checkDate() {
  var copyright=document.getElementById("footer-copyright");
  if (!copyright) return;
  var year = new Date().getFullYear();
  if (copyright.innerHTML.indexOf(year)>0) return;
  copyright.innerHTML=copyright.innerHTML.replace(/(1999\-\d{4}|1999\-xxxx)/i,"1999-"+year);
}
//------------------------------
function limitImageSize() {
  if (document.getElementById("dontresizeimages")) return true;
  if ($("body.window-overflow-allowed").length) return true;
  var maxWidth=511;
  try{
    var body = document.getElementsByTagName("body")[0];
    if (/(scc\-freecharts)/.test(body.className)) return;
  }catch(e){}
  var container = document.getElementById("alpha-inner");
  if (!container) return;
  if (container.offsetWidth) maxWidth=container.offsetWidth-10;
  if (/<div class=[\'\"]entries/i.test(container.innerHTML)) maxWidth-=30;;
  var imgs = container.getElementsByTagName("img");
  for (var i=0;i<imgs.length;i++) {
    if (imgs[i].offsetWidth && parseInt(imgs[i].offsetWidth)>maxWidth) {
      imgs[i].style.width = maxWidth +"px";
      if (imgs[i].getAttribute("width") && parseInt(imgs[i].getAttribute("width"))!= maxWidth) {
         //Safari/FF need this, but breaks IE. Above conditional diverts IE for now...
         imgs[i].setAttribute("width", maxWidth);
         imgs[i].setAttribute("height",null);
      }
    }
    else if (imgs[i].style.pixelWidth && imgs[i].style.pixelWidth>maxWidth) {
      imgs[i].style.pixelWidth = maxWidth;
    }
  }
}
//------------------------------
function changeToTables() {
  try{
    if (!$("body").hasClass("blog-data")) return;
    var isSplitQuirky=(("|".split(/\|/)).length<2);
    $(".entry-body").each(function(){
      var html = this.innerHTML;
      html=html.replace(/\s+/g," ");
      html=html.replace(/<br[^>]*>/gi,"\n");
      html=html.replace(/(\&\#0160\;|\&nbsp\;)/g," ");
      var rx1=/(\s*\n\s*\|[^\n]+\|)+/g;
      var changed=[];
      var matches1;
      while ((matches1 = rx1.exec(html)) != null)
      {
        var table="<table border='1' cellspacing='0' class='scc-typical'>";
        var rows=matches1[0].split("\n");
        var isFirstRow=true;
        for (var i=0;i<rows.length;i++){
          var row=rows[i];
          row=row.replace(/(^\s*|\s*$)/g,"");
          var isHeader=(isFirstRow && /^\|\|.+\|\|$/.test(row));
          if (!row) continue;
          var cols=(isHeader)?row.split(/\|+/):row.split(/\|/);
          //if (i==4) alert (cols.length+"\n"+row.split(/\|+/)+"\n"+row);
          if (cols.length==0) continue;
          table+=(isHeader)?"<thead><tr>":(i==0)?"<tbody><tr>":"<tr>";
          var jstart=isSplitQuirky?0:1;var jend=cols.length-(isSplitQuirky?0:1);
          for (var j=jstart;j<jend;j++){
            table+=(isHeader)?"<th "+(j==jstart?"class='first'":"")+">"+cols[j]+"</th>":
                              "<td "+(j==jstart?"class='first'":"")+">"+cols[j]+"</td>";
          }
          table+=(isHeader)?"</tr></thead><tbody>":"<tr>";
          isFirstRow=false;
        }
        table+="</tbody></table>";
        changed.push({"table":table,"start":matches1.index,"end":matches1.index+matches1[0].length});
      }
      for (var i=0;i<changed.length;i++){
        html=html.substr(0,changed[i].start)+changed[i].table+html.substr(changed[i].end);
      }
      html=html.replace(/\n/g,"<br>");
      html=html.replace(/\s\s/g," &nbsp;");
      if (changed.length>0) this.innerHTML=html;
    });
  }catch(e){}
}
//------------------------------
function zebraTables(){
  return;
  try{
    $(document).ready(function(){
      $("table.scc-zebra tr:nth-child(odd)").addClass("odd");
      $("table.scc-zebra tr:nth-child(even)").addClass("even");
    });
  }catch(e){}
}
//------------------------------
function personalizeMembersPage() {
  //still thinking...
  var b = document.getElementsByTagName("body")[0];
  if (!b || !/\bscc\-members\b/.test(b.className)) return;
  var d = document.getElementById("banner-description");
  if (!d) return;
  d.innerHTML="";
}
//------------------------------
function searchValidate(fieldName) {
  if ( !fieldName) return true; //don't stop search
  var field = document.getElementById(fieldName);
  if (!field) return true; //don't stop search
  if (!field.value || /^\s*$/.test(field.value)) return false; //stop search on blank values
  return true;
}
//------------------------------
function chartSearch(prefix) {
//never returns true, just switches page
  if (prefix==undefined) prefix="navsearch";
  var field=document.getElementById(prefix+"text");
  var opts=document.getElementById(prefix+"options");
  if (!field || !opts) return false;
  if (!field.value || /^\s*$/.test(field.value)) return false;
  var urls=["/h-sc/ui?s=",//0
	"/def/servlet/SC.pnf?c=",//1
	"/candleglance?",//2
	"/webcgi/perf.html?",//3
	"/gallery?",//4
	"/symsearch?",//5
	"/support/search.html?q="];//6];
  if (opts.selectedIndex<urls.length) {
    var url=urls[opts.selectedIndex]+encodeURIComponent(field.value);
    if (opts.selectedIndex==1) url+=",P";
    if (typeof(self) != "undefined" && typeof(top) != "undefined" && self!=top) 
      parent.location="http://stockcharts.com"+url;
    else
      window.location="http://stockcharts.com"+url;
  }
  return false;
}
//------------------------------
function multiSearch(s,rootElement) { //new version of above, changed to fit autosuggest (s is only set when autosuggest is on and rootElement is blank)
  if (typeof(rootElement)=="undefined" || $(rootElement).size()==0) rootElement=".nav-search";
  try{
  var text=encodeURIComponent($(rootElement+" input[type=text]").val().replace(/(^\s+|\s+$)/g));
  if (!text) return false; //blanks are useless
  var option=$(rootElement+" select").get(0).selectedIndex;
  if (!option) option=0;
  var urls=["/h-sc/ui?s="+text,//0
	"/def/servlet/SC.pnf?c="+text+",P",//1
	"/candleglance?"+text,//2
	"/webcgi/perf.html?"+text,//3
	"/gallery?"+text,//4
	"/symsearch?"+text,//5
	"/support/search.html?q="+text];//6
  changeLocation("http://stockcharts.com"+urls[option]);
  }catch(e){alert ("There was an error in processing this search: "+e)}
  return false;
}
//------------------------------


//------------------------------
//these functions are used by other javascript files:

function changeLocation(url){ 
//checks for a subframe and pops out if needed
  if (typeof(self) != "undefined" && typeof(top) != "undefined" && self!=top) 
    parent.location=url;
  else
    window.location=url;
}
function runNow(functionList){ 
  for (var i=0;i<functionList.length;i++){try{
    functionList[i];
  }catch(e){}}
}

function runPageReady(functionList){ //requires jquery
  for (var i=0;i<functionList.length;i++){try{
    $(document).ready(functionList[i]);
  }catch(e){}}
}

function runPageDone(functionList){
  //add any other delays here for prioritizing page-specific scripts:
  if (typeof(_SC2GLOBALS)!="undefined" && _SC2GLOBALS && _SC2GLOBALS.pageInitializing){ //will this make sc run faster?
    setTimeout(function(){runPageDone(functionList);},100);
    return;
  }
  for (var i=0;i<functionList.length;i++){try{
    if (window.addEventListener) window.addEventListener("load", functionList[i], false);
    else if (document.addEventListener) document.addEventListener("load", functionList[i], false);
    else if (window.attachEvent) window.attachEvent("onload", functionList[i]);
  }catch(e){}}
}
//------------------------------

//init:
(function(){
  runPageReady([breakFrames,activateChangeTextSize,identifyUser,changeToTables,zebraTables]);//prioritized order
  runPageDone([limitImageSize,checkDate,addAnalytics]);
})();

// highlight search terms (if st=<term> is present in the url)

function getQueryParam(name) {
    var value = "";
    var queryStr = document.location.search.slice(1);
    if (queryStr) {
        var arr = queryStr.split("&");
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].indexOf(name + "=") == 0) {
                value = arr[i].slice(name.length + 1);
                value = decodeURIComponent(value);
                break;
            }
        }
    }
    return value;
};

$.fn.highlight = function(pattern) {
    // case insensitive search (single characters are only matched if they are words by themselves)
    var re = (pattern.length>1) ? new RegExp(pattern, "i") : new RegExp("\\b" + pattern + "\\b", "i");
    var doHighlight = function(node, pattern) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.search(re);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pattern.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                $(spannode).css({'background-color': 'yellow', 'color': 'black'});
                skip = 1;
            }
        } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += doHighlight(node.childNodes[i], pattern);
            }
        }
        return skip;
    }

    return this.each(function() {
        if (pattern) {
            doHighlight(this, pattern);
        }
    });
};

var queryParam = getQueryParam("st");
if (queryParam) {
    var searchTerms = queryParam.split("+");
    for (var i = 0; i < searchTerms.length; i++) {
        $(document.body).highlight(searchTerms[i]);
    }
}
