﻿
//////////////////////
//  Google Analytics
//////////////////////
function InitializeGoogle() {
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-7083626-10']);
    _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 s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
};

/////////////
// Index
/////////////
function GenerateNewsTicker(resultCount, loaderName) {
    PullNews(resultCount, BindNewsTicker, loaderName);
};

function BindNewsTicker(msg, optFuncParms) {
    var newsContainer = optFuncParms.ElementName
    $.map(msg, function (item) {
        $('#news-contents').append('<li><div><p><a href="article.html?NewsTitle=' + item.Title.replace(/ /g, '_') + '">' + item.Title + '</a></p><p>' + item.ShortDescription + '</p></div></li>');
    });

    // Initialize ticker
    $('#news-container').vTicker({
        speed: 2000,
        pause: 10000,
        animation: 'fade',
        mousePause: true,
        showItems: 1
    });
};

function GenerateEvents(loaderName) {
    PullEvents(BindEvents, loaderName) 
};

function BindEvents(msg, optFuncParms) {
    $.map(msg, function (item) {
        $('#events-container').append('<p><strong><a href="' + item.EventSiteURL + '">' + item.Title + '</a></strong>, ' + item.DateRange + '</br></p>');
    });
};

//////////////
// News
//////////////
function GenerateNews(resultCount, loaderName) {
    PullNews(resultCount, BindNews, loaderName);
};

function BindNews(msg, optFuncParms) {
    $.map(msg, function (item) {
        $('#ulMilestoneNews').append('<li><a href="article.html?NewsTitle=' + item.Title.replace(/ /g, '_') + '">' + item.Title + '</a></li>');
    });
};

function PullPressReleases(resultCount, loaderName) {
    CallService('', '/RetrievePressReleases/JSON/' + resultCount, '', 'json', 'application/json;charset=utf-8', 'GET', BindPressReleases, {}, loaderName);
};

function BindPressReleases(msg, optFuncParms) {
    var prRow;
    $.map(msg, function (item) {
        prRow = item.Value[0];
        $('#ulChiefPR').append('<li><a href="' + prRow.URL + '">' + prRow.Title + '</a></li>\n');
    });
};

/////////////////
// News Archive
/////////////////
function GenerateNewsArchive(loaderName) {
    PullNews(100000, BindNewsArchive, loaderName);
};

function BindNewsArchive(msg, optFuncParms) {
    var currYear;
    $.map(msg, function (item) {    
        if (currYear != $.fn.FormatDate(item.StartDate, "yyyy")) {
            currYear = $.fn.FormatDate(item.StartDate, "yyyy");
            $('#ulMilestoneNews').append('<h3>' + currYear + '</h2>');
        }
        $('#ulMilestoneNews').append('<li><a href="article.html?NewsTitle=' + item.Title.replace(/ /g, '_') + '">' + item.Title + '</a></li>');        
    });
};

/////////////////
// News Article
/////////////////
function GenerateNewsArticle(newsTitle, loaderName) {
    CallService('', '/RetrieveNewsByNewsTitle/JSON/' + newsTitle + '/true/false', '', 'json', 'application/json;charset=utf-8', 'GET', BindNewsArticle, {}, loaderName);
};

function BindNewsArticle(msg, optFuncParms) {
    if (msg != null) {
        $('#ArticleTitle').html(msg.Title);
        $('#ArticleBody').html(msg.LongDescription);
    }
};

/////////////////////
// Utilities
/////////////////////
function PullNews(resultCount, successFuntion, loaderName) {
    CallService('', '/RetrieveNews/JSON/null/false/' + resultCount, '', 'json', 'application/json;charset=utf-8', 'GET', successFuntion, {}, loaderName);
};

function PullEvents(successFuntion, loaderName) {
    CallService('', '/RetrieveEvents/JSON/true/false', '', 'json', 'application/json;charset=utf-8', 'GET', successFuntion, '', loaderName);
};

function PullFeed(url, listName, loaderName) {
    CallService('', '/GetFeed/XML/', "{ 'feedUrl' : '" + url + "' }", 'xml', 'charset=utf-8', 'POST', BindFeed, { ListName: listName }, loaderName);
};

function BindFeed(msg, optFuncParms) {   
    var xmlDoc = $.parseXML($(msg).text());    
    $.map($(xmlDoc).find('item'), function (item, index) {
        if (index < 5) {
            $('#' + optFuncParms.ListName).append('<li><a href="' + $(item).find('link').text() + '">' + $(item).find('title').text() + '</a></li>\n');
        }
    });
};

/////////////////////////////////
// Common
/////////////////////////////////

function GetEndpoint(keyword) {
    //var domain = 'https://localhost:447';
    //var domain = 'http://localhost:86';
    //var domain = 'https://servicesdev.milestone.com';
    if (keyword == 'Media') {
        return domain + '/Services/ChiefMediaContentR.svc';
    }
    else if (keyword == 'Calculators') {
        return domain + '/Services/ChiefWebCalculatorsR.svc';
    }
    else if (keyword == 'Content') {
        return domain + '/Services/ChiefWebContentR.svc';
    };
};

function CallService(endpointType, url, data, dataType, contentType, type, successFunction, optFuncParms, loaderName) {
    $('#' + loaderName).show();
    $.ajax({
        type: type,
        url: '/WebServices/MilestoneProxy.svc' + url,
        data: data,
        contentType: contentType,
        dataType: dataType,
        //crossDomain: true,
        success: function (msg) {
            successFunction(msg, optFuncParms);
            $('#' + loaderName).hide();
        },
        error: function (xhr, textStatus, thrownError) {
            /* alert(url + " Service Error - Unable to pull manufacturers. TextStatus: "
            + textStatus + " ThrownError: " + thrownError); */
        }
    });
};

//////////////////////////////////
// Pull parms from query string
//////////////////////////////////
function GetUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

// Determines if an element exists
(function ($) {
    $.fn.exists = function () {
        return jQuery(this).length > 0;
    };
})(jQuery);

// Format date as provided string pattern, options
// Pattern letters
//    Letter 	Date or Time Component 	Presentation 	Examples
//    G 	Era designator 	Text 	AD
//    y 	Year 	Year 	1996; 96
//    M 	Month in year 	Month 	July; Jul; 07
//    w 	Week in year 	Number 	27
//    W 	Week in month 	Number 	2
//    D 	Day in year 	Number 	189
//    d 	Day in month 	Number 	10
//    F 	Day of week in month 	Number 	2
//    E 	Day in week 	Text 	Tuesday; Tue
//    a 	Am/pm marker 	Text 	PM
//    H 	Hour in day (0-23) 	Number 	0
//    k 	Hour in day (1-24) 	Number 	24
//    K 	Hour in am/pm (0-11) 	Number 	0
//    h 	Hour in am/pm (1-12) 	Number 	12
//    m 	Minute in hour 	Number 	30
//    s 	Second in minute 	Number 	55
//    S 	Millisecond 	Number 	978
//    z 	Time zone 	General time zone 	Pacific Standard Time; PST; GMT-08:00
//    Z 	Time zone 	RFC 822 time zone 	-0800
//
// Examples
//    "yyyy.MM.dd G 'at' HH:mm:ss z" 	2001.07.04 AD at 12:08:56 PDT
//    "EEE, MMM d, ''yy" 	Wed, Jul 4, '01
//    "h:mm a" 	12:08 PM
//    "hh 'o''clock' a, zzzz" 	12 o'clock PM, Pacific Daylight Time
//    "K:mm a, z" 	0:08 PM, PDT
//    "yyyyy.MMMMM.dd GGG hh:mm aaa" 	02001.July.04 AD 12:08 PM
//    "EEE, d MMM yyyy HH:mm:ss Z" 	Wed, 4 Jul 2001 12:08:56 -0700
//    "yyMMddHHmmssZ" 	010704120856-0700
(function ($) {
    $.fn.FormatDate = function (date, dateFormat) {
        return $.format.date(eval(new Date(parseInt(date.substr(6)))), dateFormat);
    };
})(jQuery);

