﻿var tagCookie = 'mySATags';

$(document).ready(function () {
    populateClippings();
    prepareTags();
});

function prepareTags() {
    $(".tagit")
    .mouseover(mouseoverTagAdd)
    .mouseout(mouseoutTag);
    $(".tagremove")
    .mouseover(mouseoverTagRemove);
}

function doEscape(s) {
    return s.replace(/"/g, '\"').replace(/'/g, "\'");
}

function mouseoverTagAdd(e) {
    var lb = document.createElement('A');
    lb.id = 'linkButton';
    lb.appendChild(document.createTextNode(' '));
    lb.onmouseover = function(f) {
        if (typeof lbHide_abort == 'function') lbHide_abort();
    };
    lb.onmouseout = function(f) {
        if (typeof lbHide == 'function') lbHide();
    };
    if (typeof clippingExists == 'function' && clippingExists(this.href)) {
        lb.className = 'lb_remove_red';
        lb.title = 'Remove from My Tags';
        lb.alt = lb.title;
        var url = doEscape(this.href);
        lb.href = 'javascript:void(removeTag("' + url + '"));';
    }
    else {
        lb.className = 'lb_add_green';
        lb.title = 'Add to My Tags';
        lb.alt = lb.title;
        var url = doEscape(this.href);
        var tagname = doEscape(this.innerHTML.replace(/(<[^>]+>|Related Story:)/ig, '').trim());
        lb.href = 'javascript:void(addTag("' + url + '","' + tagname + '"));';
    }
    this.parentNode.insertBefore(lb, this);
}
function mouseoverTagRemove(e) {
    var test = findPos(this);
    var x = test.x;
    var y = test.y - 4;
    var moving_box = $("#removeTag");
    moving_box.css("position", "absolute");
    moving_box.css("top", y);
    moving_box.css("left", x);
    moving_box.show();
}
function mouseoutTag(e) {
    lbHide();
}

function findPos(obj) {
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
    }
    return { x: curleft, y: curtop };
}

function lbHide() {
    lbTimeout = window.setTimeout("lbHide_do();", 1500);
}

function lbHide_do() {
    var lb;
    if (lb = document.getElementById("linkButton")) {
        lb.parentNode.removeChild(lb);
    }
}

function lbHide_abort() {
    if (window.lbTimeout) {
        window.clearTimeout(lbTimeout);
    }
}

function setCookie(name, value, expires, path, domain, secure) {
    var newValue = name + "=" + escape(value) + (path ? "; path=" + path : "");
    document.cookie = newValue;
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) {
            return null;
        }
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" + (path ? "; path=" + path : ""); //+ (domain ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function addTag(url, title) {
    lbHide_do();
    url = url.replace(/^[a-z]+:\/\/[^\/]+/, "");
    title = title.replace(/(<[^>]+>|Related Story:)/gi, "").trim();
    if (clippingExists(url)) {
        return false;
    }
    var exp = (new Date).getTime();
    exp += 43200000;
    exp = new Date(exp);
    var cookieData = getCookie(tagCookie);
    var newValue = (cookieData == null || cookieData.trim() == "" ? "" : cookieData + ";") + url + "~" + title;
    setCookie(tagCookie, newValue, exp, "/", ".sa.gov.au");
    if (!clippingExists(url)) {
        var cookieData = getCookie(tagCookie);
        if (cookieData == null || cookieData == "") {
            alert("Sorry, this tag could not be added.\n\nPlease ensure that cookies are enabled in your web browser.");
        } else {
            alert("Sorry, this tag could not be added.\n\nYou may have too many items in My Tags.");
        }
    } else {
        populateClippings(url);
        alert('Tag successfully added.');
    }
    return false;
}

function removeTag(url) {
    lbHide_do();
    var cookieData = getCookie(tagCookie);
    if (cookieData == null) {
        return false;
    }
    var removed = false;
    var clippings = cookieData.split(";");
    for (var i = 0; i < clippings.length; i++) {
        if (url.indexOf(clippings[i].split("~")[0]) != -1) {
            clippings.splice(i, 1);
            removed = true;
        }
    }
    cookieData = clippings.join(";");
    if (cookieData == "") {
        cookieData = " ";
    }
    var exp = (new Date).getTime();
    exp += 43200000;
    exp = new Date(exp);
    setCookie(tagCookie, cookieData, exp, "/", ".sa.gov.au");
    if (!removed) {
        alert("Sorry, tag could not be removed.");
    } else {
        populateClippings();
        alert('Tag successfully removed.');
    }
    return false;
}

function clippingExists(url) {
    var cookieData = getCookie(tagCookie);
    if (cookieData == null || cookieData == "") {
        return false;
    }
    var clippings = cookieData.split(";");
    //alert(url + '||||' + cookieData);
    url = decodeURI(url);
    var url_parts = url.split('/');
    var tagname = url_parts[url_parts.length - 1];
    for (var i = 0; i < clippings.length; i++) {
        //alert(tagname + '\n' + clippings[i].split("~")[1]);
        if (tagname == clippings[i].split("~")[1]) {
            return true;
        }
    }
    return false;
}

function windowPrint() {
    window.print();
}

function populateClippings(newURL) {
    var c = $("div[id$='tagz']");
    if (c != null) {
        c.innerHTML = "";
        var cookieData = getCookie(tagCookie);
        if (cookieData == null ||
            typeof cookieData == "string" && cookieData.trim() == "") {
            c.html("<p>Tags you may want to access later.</p>");
        } else {
            var clippings = cookieData.split(";");
            var html = "";
            for (var i = 0; i < clippings.length; i++) {
                var x = clippings[i].split("~");
                var highlight = false;
                var fadefrom = new Array(255, 255, 51);
                if (newURL) {
                    if (newURL.indexOf(x[0]) != -1) {
                        highlight = true;
                        for (var j = 1; j <= 10; j++) {
                            setTimeout("if (cn = document.getElementById(\"myc" + i + "\")) cn.style.backgroundColor=\"rgb(" + Math.round(fadefrom[0] + j / 10 * (255 - fadefrom[0])) + "," + Math.round(fadefrom[1] + j / 10 * (255 - fadefrom[1])) + "," + Math.round(fadefrom[2] + j / 10 * (255 - fadefrom[2])) + ")\";", j / 10 * 1000 + 500);
                        }
                    }
                }
                html += "<li><a href=\"" + x[0] + "\" class=\"tagit\">" + x[1] + "</a></li>";
            }
            c.html('<ul class="item-list">' + html + "</ul>");
            prepareTags(); // Attach events...
        }
    }
}

function clickButton(e, buttonid) {
    var bt = document.getElementById(buttonid);
    if (typeof bt == 'object') {
        if (navigator.appName.indexOf("Netscape") > (-1)) {
            if (e.keyCode == 13) {
                bt.click();
                return false;
            }
        }
        if (navigator.appName.indexOf("Microsoft Internet Explorer") > (-1)) {
            if (event.keyCode == 13) {
                bt.click();
                return false;
            }
        }
    }
}

/* Alert Carousel */
var carouselItems = 0;
var carouselHeight = 1;
var carouselDirection = true;
var carouselPosition = 0;
function carousel() {
    if ($('.weatherbox') != null) {
        carouselItems = $('.alertboxitem').length;
        if (carouselItems > 1) {
            setInterval(function() {
                if (carouselItems == carouselHeight) {
                    carouselDirection = !carouselDirection;
                } else if (!carouselDirection && carouselHeight == 1) {
                    carouselDirection = !carouselDirection;
                }

                if (!carouselDirection) {
                    carouselPosition = carouselPosition + 48;
                    carouselHeight--;
                } else {
                    carouselHeight++;
                    carouselPosition = carouselPosition - 48;
                }
                $('.alertboxscrolling').animate({ marginTop: carouselPosition.toString() }, 1500);
            }, 5000);
        }
    }
}

/* AJAX campaign rotator */

function campaignRotatorSucceededCallback(result, userContext, methodName) {
    var html = result;
    var divRotatorID = userContext;
    var divRotator = document.getElementById(divRotatorID);
    if (divRotator != null) {
        if (html.length > 0) {
            divRotator.innerHTML = html;
            //alert('done');
        }
        else 
        {
            divRotator.style.display = 'none';
        }
    }
}

function campaignRotatorFailedCallback(result, userContext, methodName) {
    var divRotatorID = userContext;
    var divRotator = document.getElementById(divRotatorID);
    if (divRotator != null) {
        divRotator.style.display = 'none';
    }
}

function drawCampaignRotator(id, divRotatorID) {
    try {
        au.gov.sa.gateway.web.webservices.LogHits.RenderCampaignRotator(id, campaignRotatorSucceededCallback, campaignRotatorFailedCallback, divRotatorID);
    } catch (exc) {
        setTimeout('drawCampaignRotator("' + id + '", "' + divRotatorID + '")', 1000);
    }
}

/* AJAX Poll */

function managePollSubmit(el) {
    var rbl = $(el);
    if (rbl.find('input:checked').val() != null) {
        var submit = rbl.parent().parent().find('input[type="button"]');
        submit.attr('disabled', false);
    }
}

function savePollResponse(rblAnswerID, pollID, contentID) {
    try {
        var answerID = $('#' + rblAnswerID).find('input:checked').val();
        au.gov.sa.gateway.web.webservices.LogHits.SavePollResponse(
            answerID,
            location.href,
            contentID,
            pollSucceededCallback, 
            pollFailedCallback,
            pollID);

        var poll = $('#Poll' + pollID);
        poll.find('.poll-main').hide();
        poll.find('.poll-thankyou').show();
    }
    catch (exc) 
    {
        setTimeout('savePollResponse("' + rblAnswerID + '", ' + pollID + ', "' + contentID + '")', 1000);
    }
}

function pollSucceededCallback(result, userContext, methodName) {
}

function pollFailedCallback(result, userContext, methodName) {
}
