// fix the mention
$(function () {
    $(".mention").each(function (i, elt) {
        var html = $(elt).html();
        html = html.replace(/^\s*\|*/, "");
        $(elt).html(html);
    });
});
// show warning
function _globalSetupBrowserWarning() {
    $(function () {
        var bIsMSIE6orless = /MSIE (5\.5|6)/.test(navigator.userAgent);
        if (bIsMSIE6orless) {
            $("#browser-warning").html("<div style='background-color: white; color: red; font-weight: bold; font-size: 14px; padding: 10px; text-align: center;'>You are viewing this website with a browser that is no longer supported.<br/>As a result, some functionality of this website may not work for you. Please upgrade to a more recent version of your browser.</div>");
        }
    });
}

// Load the weather
function _globalSetupWeather() {
    $(function () {
        $.get('plugin/weather.php',
          {},
          function (data) {
              var currentCondition = $(data).find("current_conditions condition").attr("data");
              var currentDegree = $(data).find("current_conditions temp_f").attr("data");
              var currentWind = $(data).find("current_conditions wind_condition").attr("data");
              var currentIcon = "http://google.com" + $(data).find("current_conditions icon").attr("data");

              // http://forecast.weather.gov/MapClick.php?CityName=Mcminnville&state=OR&site=PQR&lat=45.1949&lon=-123.247


              var html = "";
              html += "<div style='float: left; margin: 10px; margin-top: 12px;'>";
              html += " <a href='http://forecast.weather.gov/MapClick.php?CityName=Mcminnville&state=OR&site=PQR&lat=45.1949&lon=-123.247' target='_blank'>";
              html += "  <img src='" + currentIcon + "' alt='" + currentCondition + "' title='" + currentCondition + "'/>";
              html += " </a>";
              html += "</div>";
              html += "<div style='float: left; margin: 10px;'>";
              html += " <a href='http://forecast.weather.gov/MapClick.php?CityName=Mcminnville&state=OR&site=PQR&lat=45.1949&lon=-123.247' target='_blank'>";
              html += "  <b>Weather Now</b><br/><small>in McMinnville, OR</small><br/>";
              html += "  " + currentDegree + "&deg; | " + currentWind;
              html += " </a>";
              html += "</div>";
              html += "<div style='clear: both;'></div>";
              $("#weather-box").html(html);
          }
       );
    });
  }

// extract photos and setup fancy box
function _globalSetupFancyBox() 
{
    $(function () {
        var imgArray = new Array();
        $("#photo-slideshow .caption").css("background-color", "#eee");
        $("#photo-slideshow img").each(function (index, img) {
            var imgSrc = $(img).attr("src");
            var imgTitle = $(img).attr("title");
            var imgSrcTokens = imgSrc.split("_");
            var trueSrc = "";
           if (imgSrcTokens.length > 1) {
                // always 2 tokens => [fitbox] [size]
                for (var j = 0; j < imgSrcTokens.length - 2; j++) {
                    if (j > 0) trueSrc += "_";
                    trueSrc += imgSrcTokens[j];
                }
                trueSrc += "." + imgSrcTokens[imgSrcTokens.length - 1].split(".")[1];
            } else {
                trueSrc += imgSrcTokens[0];
            }
            trueSrc = trueSrc.replace("/thumb", "");
            imgArray.push({ 'href': trueSrc, 'title': imgTitle });
            $(img).attr('index', index);
        });
        if (imgArray.length > 1) {
            for (var i = 0; i < imgArray.length; i++) {
                if (imgArray[i].title != "") {
                    imgArray[i].title += "<br/><br/>";
                }
                imgArray[i].title += "<small>Use your mouse wheel, or click near the border of the photos to move between photos.</small>";
            }
        }
        var options = {
            'padding': 10,
            'titlePosition': 'inside',
            'transitionIn': 'none',
            'transitionOut': 'none',
            'type': 'image',
            'changeFade': 0
        };
        $("#show-lightbox").css('cursor', 'pointer').click(function () {
            $.fancybox(imgArray, options);
        });
        $("#photo-slideshow img").css('cursor', 'pointer').click(function () {
            options['index'] = $(this).attr('index');
            $.fancybox(imgArray, options);
        });
    });
}

// setup top stories
function _globalSetupTopStories() {
    $(function () {
        var format = $("#top-story-format").text();
        // format can be one of:
        // step 1 => setup the layout
        var layout = "";
        var iBoxCount = 4;
        var formatArray = new Array();
        switch (format) {
            case "2B1H": // => 2 box + 1 horizontal strip
                iBoxCount = 3; formatArray = ['B', 'B', 'H'];
                layout = "<div class='box-B1' id='box-1' style='float: left; margin-right: 8px; margin-bottom: 8px;'></div>";
                layout += "<div class='box-B1' id='box-2' style='float: right; margin-bottom: 8px;'></div>";
                layout += "<div style='clear: both;'></div>";
                layout += "<div class='box-H' id='box-3' style=''></div>";
                break;
            case "2B2H": // => 2 box +  2 horizontal strips
                iBoxCount = 4; formatArray = ['B', 'B', 'H-small', 'H-small'];
                layout = "<div class='box-B2' id='box-1' style='float: left; margin-right: 8px; margin-bottom: 8px;'></div>";
                layout += "<div class='box-B2' id='box-2' style='float: right; margin-bottom: 8px;'></div>";
                layout += "<div style='clear: both;'></div>";
                layout += "<div class='box-H-small' id='box-3' style='margin-bottom: 8px;'></div>";
                layout += "<div class='box-H-small' id='box-4' style=''></div>";
                break;
            case "1H2B": // => 1 horizontal strip + 2 box
                iBoxCount = 3; formatArray = ['H', 'B', 'B'];
                layout = "<div class='box-H' id='box-1' style='margin-bottom: 8px;'></div>";
                layout += "<div class='box-B1' id='box-2' style='float: left; margin-right: 8px;'></div>";
                layout += "<div class='box-B1' id='box-3' style='float: right;'></div>";
                layout += "<div style='clear: both;'></div>";
                break;
            case "2H": // => 2 horizontal strips
                iBoxCount = 2; formatArray = ['H', 'H'];
                layout = "<div class='box-H' id='box-1' style='margin-bottom: 8px;'></div>";
                layout += "<div class='box-H' id='box-2' style=''></div>";
                break;
            case "2C": // => 2 columns 
                iBoxCount = 2; formatArray = ['C', 'C'];
                layout = "<div class='box-C' id='box-1' style='float: left; margin-right: 8px;'></div>";
                layout += "<div class='box-C' id='box-2' style='float: right; '></div>";
                layout += "<div style='clear: both;'></div>";
                break;
            case "1C2B": // => 1 column + 2 boxes 
                iBoxCount = 3; formatArray = ['C', 'B', 'B'];
                layout = "";
                layout += "<div class='box-C' id='box-1' style='float: left; margin-right: 8px;'></div>";
                layout += "<div style='float: right; '>";
                layout += " <div class='box-B1' id='box-2' style='margin-bottom: 8px;'></div>";
                layout += " <div class='box-B1' id='box-3' style=''></div>";
                layout += "</div>";
                layout += "<div style='clear: both;'></div>";
                break;
            case "2B1C": // => 2 boxes + 1 column
                iBoxCount = 3; formatArray = ['B', 'B', 'C'];
                layout = "";
                layout += "<div class='box-C' id='box-3' style='float: right; margin-left: 8px;'></div>";
                layout += "<div style='float: left; '>";
                layout += " <div class='box-B1' id='box-1' style='margin-bottom: 8px;'></div>";
                layout += " <div class='box-B1' id='box-2' style=''></div>";
                layout += "</div>";
                layout += "<div style='clear: both;'></div>";
                break;
            case "1B": // => 1 big box
                iBoxCount = 3; formatArray = ['B'];
                layout = "";
                layout += "<div class='box-BIG' id='box-1'></div>";
                layout += "<div style='clear: both;'></div>";
                break;

            case "4B": // => 4 boxes (default)
            default:
                iBoxCount = 4; formatArray = ['B', 'B', 'B', 'B'];
                layout = "<div class='box-B1' id='box-1' style='float: left; margin-right: 8px; margin-bottom: 8px;'></div>";
                layout += "<div class='box-B1' id='box-2' style='float: right; margin-bottom: 8px;'></div>";
                layout += "<div style='clear: both;'></div>";
                layout += "<div class='box-B1' id='box-3' style='float: left; margin-right: 8px;'></div>";
                layout += "<div class='box-B1' id='box-4' style='float: right;'></div>";
                layout += "<div style='clear: both;'></div>";
                break;
        }
        $("#top-story-others").html(layout);

        $(".top-story-list .top-story-box").each(function (i, elt) {
            var sItemType = $(elt).find(".item").attr("itemType");
            var html = "";
            var bPlaceHolder = false;
            if (sItemType == 'article') {
                // this item is an article => prep it
                var category = $(elt).find(".category").html();
                var title = $(elt).find(".title").html();
                var mention = $(elt).find(".mention").html();
                var excerpt = $(elt).find(".excerpt").html();
                var summary = $(elt).find(".summary").html();
                var photoSmall = $(elt).find(".photo-small").html();
                var photoBig = $(elt).find(".photo-big").html();
                var photoBigLeft = $(elt).find(".photo-big-left").html();
                var photoPosition = $(elt).find(".photo-position").html().trim();
                if (photoPosition == "") photoPosition = "top";
                if (i == 0) {
                    // lead story
                    html = "";
                    if (photoPosition == "left") {
                        html += "<div style='float: left; margin-bottom: 5px; margin-right: 5px;'>" + photoBigLeft + "</div>";
                        html += "<h1>" + title + "</h1>";
                    } else if (photoPosition == "right") {
                        html += "<div style='float: right; margin-bottom: 5px; margin-left: 5px;'>" + photoBigLeft + "</div>";
                        html += "<h1>" + title + "</h1>";
                    } else {
                        html += "<div style='margin-bottom: 5px;'>" + photoBig + "</div>";
                        html += "<h1>" + title + "</h1>";
                    }
                    html += "<p>";
                    html += category + " &#160; " + mention + "<br/>" + excerpt;
                    html += "</p>";
                    html += "<div style='clear: both;'></div>";
                } else if (i <= iBoxCount) {
                    // other stories
                    switch (formatArray[i - 1]) {
                        case 'B':   // box 
                            html += "<div style='padding: 5px;'>";
                            html += "<p>" + category + mention + "</p>";
                            html += "<h2>" + title + "</h2>";
                            if (photoSmall != "") {
                                html += "<div style='float: left; margin-right: 5px; margin-bottom: 5px; margin-top: 2px;'>" + photoSmall + "</div>";
                            }
                            html += "<p>" + excerpt + "</p>";
                            html += "<div style='clear: both;'></div>";
                            html += "</div>";
                            break;
                        case 'H':   // horizontal 
                        case 'H-small': // horizontal thin
                            html += "<div style='padding: 5px;'>";
                            if (photoSmall != "") {
                                html += "<div style='float: left; margin-right: 5px; margin-bottom: 5px; margin-top: 2px;'>" + photoSmall + "</div>";
                            }
                            html += "<p>" + category + mention + "</p>";
                            html += "<h2>" + title + "</h2>";
                            html += "<p>" + excerpt + "</p>";
                            html += "<div style='clear: both;'></div>";
                            html += "</div>";
                            break;
                        case 'C':   // column
                            html += "<div style='padding: 5px;'>";
                            html += "<p>" + category + mention + "</p>";
                            html += "<h2>" + title + "</h2>";
                            if (photoSmall != "") {
                                html += "<div style='float: left; margin-right: 5px; margin-bottom: 5px; margin-top: 2px;'>" + photoSmall + "</div>";
                            }
                            html += "<p>" + excerpt + "</p>";
                            html += "<div style='clear: both;'></div>";
                            html += "</div>";
                            break;
                    }

                }
            } else if (sItemType == 'script') {
                // this is assumed to be a script
                html += "<div style='padding: 5px;'>";
                html += $(elt).find(".code").html();
                html += "</div>";
            } else {
                // anything else -> drop it directly into the box.
                html += "<div style='padding: 5px;' class='placeholder" + i + "'>";
                html += "</div>";
                bPlaceHolder = true;
            }

            if (i == 0) {
                $("#top-story-lead").html(html);
            } else if (i <= iBoxCount) {
                $("#top-story-others #box-" + i).append(html);
                if (bPlaceHolder) {
                    $("#top-story-others .placeholder" + i).append($(elt));
                }
            }
        });
        $("#top-story-others").append("<div style='clear: both;'></div>");
    });

}

// home and section middle boxes where 4 ads are layed out below the top stories quadrant
function _globalSetupMiddleAdBoxes() {
    $(function () {
        // add a border to the last box
        $(".middle-box-list .middle-box").last().css("border", "none");
        var combinedHtml = "";
        $(".middle-box-list .middle-box").each(function (i, elt) {
            combinedHtml += $(elt).html().trim();
        });
        if (combinedHtml == "") {
            $(".middle-box-list").remove();
        }
    });
}

// main bar setup: 2 column rows on the home page
function _globalSetupHomeRowBoxes() {
    $(function () {
		var barCount = 4;
		for (var k = 1; k <= barCount; k++) {
		  if ($(".row-box-list .row-box-"+k).html().trim() == "") continue;
		  var itemArray = $(".row-box-list .row-box-"+k);
		  if (k > 1 && itemArray.length > 0) {
			//alert('got k='+k+', item length ='+itemArray.length+' items');
			//if (k >= 2) {
			//	alert($(itemArray[0]).html());
			//}
			$(".category-row-list").append("<div class='category-divider'></div>");
		  }
		  for (var i = 0; i < itemArray.length; i += 2) {
			  if (i > 0) {
				//alert(' -- sub got k='+k+', i ='+i+' items');
				$(".category-row-list").append("<div class='category-divider'></div>");
			  }
			  var html = "<table class='category-row' style='width: 100%;' cellspacing='0' cellpadding='2'><tr>";
			  if (i + 1 < itemArray.length) {
				html += "<td class='category-box left placeholder-"+k+"-" + i + "' valign='top'></td>";
				html += "<td class='category-box right placeholder-"+k+"-" + (i + 1) + "' width='50%' valign='top'></td>";
			  } else {
				html += "<td class='category-box placeholder-"+k+"-" + i + "' valign='top'></td>";
			  }
			  html += "</tr></table>";
			  
			  $(".category-row-list").append(html);
			  $(".category-row-list .placeholder-"+k+"-" + i).append($(itemArray[i]));
			  if (i + 1 < itemArray.length) {
				$(".category-row-list .placeholder-"+k+"-" + (i + 1)).append($(itemArray[i + 1]));
			  }
		  }
		}
		$(".category-row-list").append("<div style='clear: both;'></div>");
    });
}
// main bar setup: 1 column rows on the section page
function _globalSetupSectionRowBoxes() {
    $(function () {
        var itemArray = $(".row-box-list .row-box");
        for (var i = 0; i < itemArray.length; i++) {
            var html = "<div class='category-row' style='padding: 2px;'><div class='category-box placeholder" + i + "'></div></div>";

            $(".category-row-list").append(html);
            $(".category-row-list .placeholder" + i).append($(itemArray[i]));
            // remove the second column top ruler
            $(".category-row-list .placeholder" + i).find("td .ruler").first().remove();
            // add dotted border on the td's
            $(".category-row-list .placeholder" + i).find("td:even").addClass("left");
        }
    });
}

// side bar most read, and most commented boxes
function _globalSetupMostReadBox() {
    $(function () {
        $('#most-tab .tab-list .tab').css('display', 'none');
        $('#most-tab .button-list .button').each(function (index) {
            $(this).attr('index', index);  // save the index into an attribute so that we can retrieve it later on (at click time)
            $(this).click(function () {
                var index = $(this).attr('index');  // 'this' references the button clicked. So we add an index 
                $('#most-tab .button-list .button').removeClass('selected');
                $(this).addClass('selected');
                $('#most-tab .tab-list .tab').each(function (index2) {
                    $(this).css('display', 'none'); // this references the tab
                    if (index2 == index) {
                        $(this).css('display', 'block');
                    }
                });
            });
        });
        $('#most-tab .button-list .button:first').click();
    });
}

// setup the article email dialog box
var __oEmailBoxDialog = null;
function _globalSetupEmailBox() {
    $(function () {
        // display dialog box when button email button is clicked.
        $("#email-box-button").click(function () {
            if (__oEmailBoxDialog != null) {
                __oEmailBoxDialog.hide();
                __oEmailBoxDialog = null;
            }
            __oEmailBoxDialog = new Boxy('#email-box', { title: 'Send Email', modal: true });
            var pos = __oEmailBoxDialog.getPosition();
            if (pos[1] < 50) {
                pos[1] = 50;
                __oEmailBoxDialog.moveTo(pos[0], pos[1]);
            }
        });
        // hide the box when submit is clicked (although we don't really need to do that.
        $("#email-box-submit").click(function () {
            __oEmailBoxDialog.hide();
            return true;
        });

        // trigger the dialog box if there was an error
        var error = $("#email-box-message").html().trim();
        if (error != "") {
            $("#email-box-button").click();
        }
    });
}


