var utl = ninemsn.AP.Util;
var cfg = ninemsn.AP.Config;
var me = this;
var horoscopeDatesSpans = new Array("March 21 <br/> April 19", "April 20 <br/> May 20", "May 21 <br/> June 21", "June 22 <br/> July 22", "July 23 <br/> August 22", "August 23 <br/> September 22", "September 23 <br/> October 23", "October 24 <br/> November 21", "November 22 <br/> December 21", "December 22 <br/> January 19", "January 20 <br/> February 18", "February 19 <br/> March 20");
var horoscopeNames = new Array("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces");
var horoscopeStartDates = new Array("21/03", "20/04", "21/05", "22/06", "23/07", "23/08", "23/09", "24/10", "22/11", "22/12", "20/01", "19/02");
var horoscopeEndDates = new Array("19/04", "20/05", "21/06", "22/07", "22/08", "22/09", "23/10", "21/11", "21/12", "19/01", "18/02", "20/03");
var rolloverImages = new Array(); //array of all large horoscope icons (50 x 50)
var _profile;
var horoURLs = new Array();

function initHoro() {

    if (document.getElementById('contentHoroscope') == undefined)
        return;


    cfg.HttpTransferURL = "http://data.ninemsn.com.au/NHHttpTransfer/GetNHHttpTransfer.aspx?domain={0}&fetchURL={1}&verstamp=0.9367741208532384";
    cfg.horo_domain = "astrosurf.ninemsn.com.au";
    cfg.horo_provider = "Astrocentre";
    //COMMENT cfg.horo_feedURL = "http://astrosurf.ninemsn.com.au/astrosurf/feeds/MyMsnDailyFile_Feed.aspx";
    

    //  cfg.horo_providerURL	= "http://ninemsn.com.au/astrosurf";
    cfg.horo_providerURL = "http://astrology.msn.co.nz/astrosurfnz/";


    // cfg.horo_providerURL	= "";
    cfg.horo_loveURL = "http://astrosurf.ninemsn.com.au/astrosurf/HPAstroLove.aspx?Af=-1300";
    cfg.horo_healthURL = "http://astrosurf.ninemsn.com.au/astrosurf/HPTarot.aspx?Af=-1300";
    cfg.horo_careerURL = "http://astrosurf.ninemsn.com.au/astrosurf/HPAstroCareer.aspx?Af=-1300";
    // cfg.horo_postURL		  = "http://astrosurf.ninemsn.com.au//astrosurf/Default.aspx";

    cfg.horo_postURL = "http://msn.co.nz/astrology";

    cfg.horo_defHoroId = 0;
    cfg.cookieNameHoro = "horopref";

    //var id			= p_modId;
    var me = this;
    _profile = new utl.Profile(cfg.cookieNameHoro);
    var pref = _profile.horoscopePref;

    var me = this;

    var horoscopeItems = null; 	//contains array of daily horoscope text
    var titleDiv = null; 			//container of horo icon, horo name and date
    var descriptionDiv = null; 	//container of daily description
    var currentHoroscopeId = 0; 	//currently perssisting horroscope
    _profile = pref;

    p_elSource = document.getElementById("contentHoroscope");
    me.element = p_elSource;
    me.cfwContainer = null;
    //Build array of thumbnail horoscope images.
    for (var i = 0; i < 12; i++) {
        var img = new Image(50, 50);
        img.src = "/img/horoscope/" + i + ".gif";
        rolloverImages[i] = img;
    }
    
   RenderContent();

}

// load the data from the service
function load(url) {
    // alert("load");
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url + '&_=' + Math.round(Math.random() * 10000000);
    document.getElementsByTagName('head')[0].appendChild(script);
}

function loadNZHoroData() {
    // alert("loadNZHoroData");
    load('http://data.ninemsn.com.au/Services/Service.axd?ServiceName=NZHoroscopes&ServiceAction=Get&SkipXSLT=false&ServiceFormat=JSON&callback=displayNZHoroData')
    return false;

}

function RenderContent() {
    // alert("RenderContent ");
    /*  Prepare element */
    p_elSource = document.getElementById("contentHoroscope");
    p_elSource.innerHTML = "";
    //
    var postForm = document.createElement("form");
    p_elSource.appendChild(postForm);
    postForm.id = "horo_zodiacForm";
    postForm.name = "horo_zodiacForm";
    postForm.method = "POST";
    postForm.action = cfg.horo_postURL;

    var DMFChoosenSign = document.createElement("input");
    DMFChoosenSign.type = "hidden";
    DMFChoosenSign.id = "DMFChoosenSign";
    DMFChoosenSign.name = "DMFChoosenSign";
    DMFChoosenSign.value = "";
    postForm.appendChild(DMFChoosenSign);

    var div = document.createElement("div");
    me.cfwContainer = div;

    postForm.appendChild(div);

    /*  Display temporary loading message */
    utl.showLoading(div);

    //COMMENT var qd = (cfg.horo_feedURL.indexOf("?") == -1) ? "?" : "&";

    /*  Encode URI (TODO: fix CFW so that we can just do encodeUri) */
    //COMMENT var uri = cfg.horo_feedURL.replace("&", "%26");

    //make call to get horoscope XML data
    
    //COMMENT _Url = cfg.HttpTransferURL.format(cfg.horo_domain, escape(cfg.horo_feedURL));
    //COMMENT Ninemsn.Site.NH.FeedReader.Get(_Url, me._CfwContentCallback);
    loadNZHoroData();

};






function displayNZHoroData(responseElement) {
    // alert("displayNZHoroData");
    // alert("responseElement = " + responseElement);
//COMMENT this._CfwContentCallback = function(responseElement) {

//COMMENT var data = responseElement.HttpTransferResult["cp:CONTENT"];
var data = responseElement.HttpTransferResult["CONTENT"];
    me.cfwContainer.innerHTML = "";
    me.cfwContainer.style.padding = "0px";
    me.cfwContainer.style.paddingTop = "0px";

    horoscopeItems = ParseHoroscope(data);
    var iconContainer = document.createElement("div");
    iconContainer.id = "IconsContainer";
    me.cfwContainer.appendChild(iconContainer);

    iconContainer.style.marginLeft = "0px";
    iconContainer.style.borderBottom = "0px dotted #b4b4b4";
    iconContainer.style.marginBottom = "0px";
    iconContainer.style.paddingBottom = "4px";
    //iconContainer.style.paddingTop="4px";
    //iconContainer.style.paddingLeft="5px";

    //iconContainer.style.display = "inline";
    for (var i = 0; i < 12; i++) {
        //container for every horoscope icon thumbnail
        var iconEl = document.createElement("span");
        iconEl.className = "horoImgs";
        var iconImgObj = new HoroscopeIcon(i, iconEl, me);
        //iconImgObj = null;
        iconImgObj.initialize();
        iconEl.title = horoscopeNames[i];
        iconContainer.appendChild(iconEl);
    }

    //container for the horoscope image, name and date
    titleDiv = document.createElement("div");
    titleDiv.id = "titleDiv";
    me.cfwContainer.appendChild(titleDiv);

    //container for the main horoscope text
    descriptionDiv = document.createElement("div");
    descriptionDiv.id = "descriptionDiv";
    me.cfwContainer.appendChild(descriptionDiv);

    //container to house provider info at the bottom
    me.cfwContainer.appendChild(me.buildFooter());

    //get previous preference
    if (_profile)
        currentHoroscopeId = _profile;
    else { //need to calculate user preference with regards to DOB
        //set a default in case of error
        currentHoroscopeId = cfg.horo_defHoroId;
    }

    //display currently selected horoscope
    me.DisplaySign(currentHoroscopeId);
    me.SetSign(null);
    hideLoading("ajaxloadinghoro");
    me.isInitialized = true;
}


this.buildFooter = function() {
    //container to house provider info at the bottom
    var providerDiv = document.createElement("div");
    providerDiv.id = "providerDiv";
    providerDiv.className = "horo_bottom_links gen_mod_border_top";
    //providerDiv.innerHTML="<br>Powered by DOM&reg;.";

    var poweredBy = document.createElement("span");

    providerDiv.appendChild(poweredBy);
    poweredBy.className = "horo_poweredBy";
    poweredBy.innerHTML = "Read your full <a href='{0}' id='horo_poweredBy_link'>horoscope</a>".format(cfg.horo_providerURL, cfg.horo_provider);

    utl.addBottomDiv(providerDiv);

    return providerDiv;
}

/* /// <summary>Displays the specified horoscope.</summary> */
/* /// <param name="horoscopeId">The horoscope id that is to be displayed.</param> */
/* /// <remarks>If horoscopeId is null, displays the currently set horoscope.</remarks> */
this.DisplaySign = function(horoscopeId) {
    if (horoscopeId == null)
        horoscopeId = currentHoroscopeId;

    if (horoscopeItems && horoscopeItems.length > horoscopeId && horoscopeItems[horoscopeId] != null) {
        fixInnerHTML(descriptionDiv, horoscopeItems[horoscopeId]);
    }
    else {
        //renderModuleDown(id,me.cfwContainer,null)
    }
    //var link = document.getElementById("horo_poweredBy_link");
    //link.setAttribute("href", horoURLs[horoscopeId])        
    
    //me.cfwContainer.innerHTML="<div style='padding:10px;'>An error has occoured.</div>";
};

function ParseHoroscope(data) {
    // alert("data = " + data);
    if (!data)
        return null;
    var items = new Array();
    for (var k in data) {
        
        for (var i = 0; i < data[k].length; i++) {
            
            //COMMENT if (data[k][i]["cp:ABSTRACT"] != undefined) {
            if (data[k][i]["ABSTRACT"] != undefined) {
                
                var horoscope = "";
                var signId = null;
                //COMMENT horoscope = data[k][i]["cp:ABSTRACT"];
                horoscope = data[k][i]["ABSTRACT"];

                if (horoscope.length > 135) {
                    horoscope = horoscope.substr(0, 135);
                }

                descArr = horoscope.split(".");
                var nCtr = 0;

                //// alert(descArr.length);
                if (descArr.length > 2) {
                    horoscope = descArr[0] + "." + descArr[1];
                }

                
                var URL = data[k][i]["DATA"]["URL"].value;

                if (URL != undefined) {
                    horoscope = horoscope + " ... <a href='" + URL + "'>(more)</a>";
                }
                else {
                    horoscope = horoscope + " ...";
                }


                //COMMENT signId = parseInt(data[k][i]["cp:DATA"].Sequence, 10);

                //COMMENT signId = parseInt(data[k][i]["DATA"].Sequence, 10);
                signId = parseInt(data[k][i]["DATA"].SEQUENCE, 10);
                if (signId != null && horoscope != "") {
                    items[signId - 1] = horoscope;
                    horoURLs[signId - 1] = URL;
                }
            }
        }
        if (items.length > 0)
            break;
    }
    return items;
}


this.SetSign = function(newId) {
    titleDiv.innerHTML = "";
    if (newId == null)
        newId = currentHoroscopeId;

    //place holder for horo icon
    var titleImg = document.createElement("div");
    titleImg.id = "titleImg";
    titleDiv.appendChild(titleImg);

    //(50 x 50) horo icon 
    //var img=document.createElement("img");
    //img.src=rolloverImages[newId].src;
    var img = rolloverImages[newId];
    img.removeNode = "true";
    img.alt = horoscopeNames[newId];

    utl.attachEventCallback(img, "onclick", me.ZodiacLinkClick, newId);
    titleImg.appendChild(img);

    //block containing horo name and data span
    var titleText = document.createElement("div");
    titleText.id = "titleText";
    titleDiv.appendChild(titleText);


    var titleAnchor = document.createElement("<span>");
    titleAnchor.id = "titleAnchor";
    fixInnerHTML(titleAnchor, "<b>" + horoscopeNames[newId] + "</b>");

    titleAnchor.title = horoscopeNames[newId];
    titleText.appendChild(titleAnchor);

    var titleDates = document.createElement("span");
    titleDates.id = "titleDates";

    titleText.appendChild(titleDates);

    fixInnerHTML(titleDates, horoscopeDatesSpans[newId]);
    //titleText.innerHTML="<B><a href=\"javascript:\">"+horoscopeNames[newId]+"</a></B><br>"+horoscopeDatesSpans[newId];
};

this.ZodiacLinkClick = function(signId) {
    document.getElementById("DMFChoosenSign").value = signId;
    document.getElementById("horo_zodiacForm").submit();

    window.event.returnValue = false; //returns false for firefox
    return false;
};

HoroscopeIcon = function(m_id, parentSpan, horoContainer) {
    var imgObj = null; //actual html img object

    /* /// <summary>Object initializer method.</summary> */
    /* /// <remarks>Called to initilise the object.</remarks> */
    this.initialize = function() {
        imgObj = document.createElement("img");
        //imgObj.src="/img/horoscope/i"+m_id+".gif";
        imgObj.src = "/img/horoscope/i" + m_id + ".jpg";
        imgObj.width = "23";
        imgObj.height = "23";
        imgObj.style.padding = "0 0 0 0";
        imgObj.style.border = "none";
        imgObj.style.cursor = "pointer";
        utl.attachEvent(imgObj, "onmouseover", u);
        utl.attachEvent(imgObj, "onmouseout", v);
        utl.attachEvent(imgObj, "onclick", w);
        parentSpan.appendChild(imgObj);
    };

    /* /// <summary>Function call when the 'onmouseover' event is fired.</summary> */
    /* /// <remarks>Highlight's this horo thumbnail icon and displays the relevant horoscop info.</remarks> */
    function u() {
        imgObj.style.border = "solid 0px #9a9a9a";
        horoContainer.SetSign(m_id);
        horoContainer.DisplaySign(m_id);
    };

    /* /// <summary>Function call when the 'onmouseout' event is fired.</summary> */
    /* /// <remarks>Clear's the information that was displayed for this horo thumbnail icon.</remarks> */
    function v() {
        imgObj.style.border = "none";
        horoContainer.SetSign(null);
        horoContainer.DisplaySign(null);
    };

    /* /// <summary>Function call when the 'onclick' event is fired.</summary> */
    /* /// <remarks>Set's the preference to the current horoscope.</remarks> */
    function w() {
        // alert(m_id);
        horoContainer.PersistSign(m_id);
        horoContainer.DisplaySign(m_id);
    };
};
/* /// <summary>Save's the users preference when they select a specific horoscope.</summary> */
/* /// <param name="newId">The horoscope id that is to be saved.</param> */
this.PersistSign = function(newId) {
    currentHoroscopeId = newId;
    writeCookie(cfg.cookieNameHoro, newId, "");
};
/**
Load the module in the load event
**/
window.onload = function() {
    try {
        init();
        initHoro();
    } catch (e) { }
}




/* /// <summary>Fix for innerHTML problems in IE</summary> */
/* /// <param name="parentElement"></param> */
/* /// <param name="Elementvalue"></param> */
function fixInnerHTML(parentElement, Elementvalue) {
    _old = parentElement.getElementsByTagName("div");
    if (_old.length > 0)
        parentElement.removeChild(_old[0]);
    _tmp = document.createElement("div");
    _tmp.innerHTML = Elementvalue;
    parentElement.appendChild(_tmp);
    _tmp = null;
}

function hideLoading(idName) {
    try {
        elContainer = document.getElementById(idName);
        elContainer.style.display = "none";
    }
    catch (ex) {
    }
}











