//****
//Homepage article transitions
//****
var nCurrentLead = 0;
var nFadeOutOpacity = 100;
var nFadeInOpacity = 0;
var nClickedArticleLeadLink = -1;
var timerArticleLeads;

function initLeads()
{
    //set the first article to display
    nClickedArticleLeadLink = 0;

    //initiate the change
    changeLeads();              
}

// move to the previous article
function changeLeads_Prev()
{
    // stop moving at the first article
    if(nCurrentLead == 0)
    {
        nClickedArticleLeadLink = 0;
    }
    else
    {
        nClickedArticleLeadLink = nCurrentLead - 1;
    }
    
    // clear the timer
    clearTimeout(timerArticleLeads);
    
    //initiate the change
    changeLeads();
}

// move to the next article
function changeLeads_Next()
{
    // stop moving at the last article
    if(nCurrentLead == 4)
    {
        nClickedArticleLeadLink = 4;
    }
    else
    {
        nClickedArticleLeadLink = nCurrentLead + 1;
    }
    
    // clear the timer
    clearTimeout(timerArticleLeads);
    
    // initiate the change
    changeLeads();
}

// move to the selected article
function changeLeads_onClick(nArticleLeadLink)
{
    // adjust the story number for the array
    nClickedArticleLeadLink = nArticleLeadLink;

    // clear the timer
    clearTimeout(timerArticleLeads);
    
    // initiate the change
    changeLeads();
}

// change the article
function changeLeads()
{
    // set the previous article to the last current
    var nPreviousLead = nCurrentLead;

    // if a change has been initated outside of time
    if(nClickedArticleLeadLink >= 0)
    {
        nCurrentLead = nClickedArticleLeadLink; // set the current to the selected
        nClickedArticleLeadLink = -1; // clear out the selected for next time
    }
    else
    {
        if(nCurrentLead != 4) // determine if we reached the end
        {nCurrentLead = nCurrentLead + 1;} // if not continue to the next article
        else 
        {nCurrentLead = 0;} // or move to the first article
    }
    
    // change the selected story number
    for(i=0;i<=4;i++) {
        document.getElementById("article_lead_" + i).style.display = "none";
        document.getElementById("article_lead_" + i + "_link").className = "story"; // set all to normal
    }

    document.getElementById("article_lead_" + nCurrentLead).style.display = "block";
    document.getElementById("article_lead_" + nCurrentLead + "_link").className = "story selected"; // select the current lead aricle link
    
    timerArticleLeads = setTimeout("changeLeads()", 10000); // initate the time to change automatically
}

/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function echeck(str) 
{
    var at="@";
    var dot=".";
    var lat=str.indexOf(at);
    var lstr=str.length;
    var ldot = str.indexOf(dot);
    
    if (str.indexOf(at)==-1){
        alert("Invalid E-mail Address");
        return false;
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
        alert("Invalid E-mail Address");
        return false;
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        alert("Invalid E-mail Address");
        return false;
    }

    if (str.indexOf(at,(lat+1))!=-1){
        alert("Invalid E-mail Address");
        return false;
    }

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("Invalid E-mail Address");
        return false;
    }

    if (str.indexOf(dot,(lat+2))==-1){
        alert("Invalid E-mail Address");
        return false;
    }

    if (str.indexOf(" ")!=-1){
        alert("Invalid E-mail Address");
        return false;
    }

    return true;
}

function ValidateForm() {

    var emailID = document.getElementById("txtEmail");

    if ((emailID.value==null)||(emailID.value=="")){
        alert("Please Enter your Email ID");
        emailID.focus();
        return false;
    }
    if (echeck(emailID.value)==false){
        emailID.value="";
        emailID.focus();
        return false;
    }
    
    return true
}

function submitNewsletter() 
{
    var bValid = ValidateForm();

    if (bValid) {
        window.open('', 'newsletter', 'menubar=1,resizable=1,width=350,height=250');

        var newsletterForm = document.getElementById('aspnetForm');
        newsletterForm.action = 'http://www.artandantiquesmag.com/code/newsletter.asp';
        newsletterForm.target = 'newsletter';
        newsletterForm.submit();
        newsletterForm.action = '';
        newsletterForm.target = '_self';
    }

    return false;
}


//**************************************************************************
//Featured Gallery transitions
//**************************************************************************

var nCurrentGallery = 0;
var arrGallery = new Array();
var arrGalleryImpressionUrl = new Array();
var arrGalleryName = new Array();
var nFadeOutOpacity = 100;
var nFadeInOpacity = 0;
var nClickedGalleryLink = -1;
var timerGalleries;
var category = "Home";
var jsonContent;
var bLoopGalleries = false;
var objGalleriesContainer;
var arrCountries = new Array();
var arrStates = new Array();
var arrCities = new Array();
var nFilteredResults = 0;
var nFilteredPages = 0;
var objectEventTracker = pageTracker._createEventTracker("Featured Galleries");

// populates country drop down
function buildCountries() {
    var strCountries = " ";
    var x = 1;

    for (i = 0; i < jsonContent.gallery.length; i++) {
        if (strCountries.indexOf(jsonContent.gallery[i].address.country) < 0) {
            strCountries += jsonContent.gallery[i].address.country + ",";
            document.getElementById("country").options[x] = new Option(jsonContent.gallery[i].address.country, jsonContent.gallery[i].address.country);
            x++;
        }
    }
}

function buildStates(country) {
    var strStates = "";
    var x = 1;

    objState = document.getElementById("state");
    objCity = document.getElementById("city");

    // clear the state drop-down
    for (i = objState.options.length; i >= 0; i--) {
        objState.remove(i);
    }
    objState.options[0] = new Option("", "");

    // clear the city drop-down
    for (i = objCity.options.length; i >= 0; i--) {
        objCity.remove(i);
    }
    objCity.options[0] = new Option("", "");

    // rebuild the state drop-down based on the new country selected
    for (i = 0; i < jsonContent.gallery.length; i++) {
        if ((jsonContent.gallery[i].address.country == country) && (strStates.indexOf(jsonContent.gallery[i].address.state_or_prov) == -1)) {
            strStates += jsonContent.gallery[i].address.state_or_prov + ",";
            objState.options[x] = new Option(jsonContent.gallery[i].address.state_or_prov, jsonContent.gallery[i].address.state_or_prov);
            x++;
        }
    }
}

function buildCities(country, state) {
    var strCities = "";
    var x = 1;

    objCity = document.getElementById("city");

    // clear the city drop-down
    for (i = objCity.options.length; i >= 0; i--) {
        objCity.remove(i);
    }
    objCity.options[0] = new Option("", "");

    for (i = 0; i < jsonContent.gallery.length; i++) {
        if ((jsonContent.gallery[i].address.country == country) && (jsonContent.gallery[i].address.state_or_prov == state) && (strCities.indexOf(jsonContent.gallery[i].address.city))) {
            strCities += jsonContent.gallery[i].address.city + ",";
            objCity.options[x] = new Option(jsonContent.gallery[i].address.city, jsonContent.gallery[i].address.city);
            x++;
        }
    }
}

function searchstring(str, txt) {
    str = str.toLowerCase();
    return str.search(txt.toLowerCase());
}

function rewriteGalleries(country, state, city, txt, nPageSize, nPage) {
    var url = "/code/featured_galleries_tracker.asp?"
    //var url = "/code/featured_galleries_tracker.asp?"
    var qsImpression;
    var qsClick;
    var n = 0;
    var y = 0;
    var arrMonthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    var dDate = new Date();
    var strCurrentMonth = arrMonthNames[dDate.getMonth()];
    var pagingResponse = "";
    var searchTxt = "";
    var alignImage = "";
    var alignText = "";
    var styleGallery = "";

    finalResponse = " ";

    // Loop over gallery length.
    for (i = 0; i < jsonContent.gallery.length; i++) {
        if (((country == "") || (jsonContent.gallery[i].address.country == country)) && ((state == "") || (jsonContent.gallery[i].address.state_or_prov == state)) && ((city == "") || (jsonContent.gallery[i].address.city == city))) {
            searchTxt = jsonContent.gallery[i].name + jsonContent.gallery[i].address.street + jsonContent.gallery[i].address.city + jsonContent.gallery[i].address.state_or_prov + jsonContent.gallery[i].phone + jsonContent.gallery[i].description + jsonContent.gallery[i].work + jsonContent.gallery[i].artist;

            if ((txt == "") || (searchstring(searchTxt, txt) > -1)) {
                if ((bLoopGalleries) || (n >= (nPage * nPageSize))) {
                    if ((bLoopGalleries) || (y < nPageSize)) {


                        // alternate Images and Texts if not Looping
                        if (!bLoopGalleries) {
                            if (((y + 1) / 2 == 1) || ((y + 1) / 2 == 2)) {
                                alignImage = "style=\"float:left;\"";
                                alignText = "style=\"float:right;\"";
                            }
                            else {
                                alignImage = "style=\"float:right;\"";
                                alignText = "style=\"float:left;\"";
                            }
                            styleGallery = "style=\"position:relative;display:block;margin-bottom:0px;\"";
                        }

                        arrGallery[n] = "gallery_" + n;
                        qsClick = ""
                        qsImpression = ""

                        qsClick += "action=click";
                        qsClick += "&aid=" + jsonContent.gallery[i].id;
                        qsClick += "&name=" + window.escape(jsonContent.gallery[i].name);
                        qsClick += "&url=" + jsonContent.gallery[i].website;

                        qsImpression += "action=impress";
                        qsImpression += "&aid=" + jsonContent.gallery[i].id;
                        qsImpression += "&name=" + window.escape(jsonContent.gallery[i].name);
                        qsImpression += "&url=" + jsonContent.gallery[i].website;

                        if (!bLoopGalleries) {
                            //new Ajax.Request(qsImpression, {method: 'get'}); // Track the impression
                            //pageTracker._trackPageview(window.escape("/Featured-Galleries/Impressions/" + jsonContent.gallery[i].name)); // and on Google Analytics
                            //objectEventTracker._trackEvent("Impression", jsonContent.gallery[i].name);
                        }
                        else {
                            arrGalleryImpressionUrl[i] = url + qsImpression;
                            arrGalleryName[i] = jsonContent.gallery[i].name;
                        }

                        finalResponse += "<div class=\"FeaturedAdvertiser\" id=\"gallery_" + n + "\"" + styleGallery + ">\n";
                        finalResponse += "    <div class=\"text\" " + alignText + ">\n";
                        finalResponse += "        <h3><a href=\"" + url + qsClick + "\" target=\"_blank\" onclick=\"objectEventTracker._trackEvent('Click','" + jsonContent.gallery[i].name + "');\">" + jsonContent.gallery[i].name + "</a></h3>\n";
                        finalResponse += "        <address><a href=\"" + url + qsClick + "\" target=\"_blank\" onclick=\"objectEventTracker._trackEvent('Click','" + jsonContent.gallery[i].name + "');\">\n";
                        finalResponse += "        <span class=\"address\">" + jsonContent.gallery[i].address.street + "</span><br />\n";
                        finalResponse += "        <span class=\"city\">" + jsonContent.gallery[i].address.city + "</span>, \n";
                        finalResponse += "        <span class=\"state\">" + jsonContent.gallery[i].address.state_or_prov + "</span><br />\n";
                        finalResponse += "        <span class=\"phone\">" + jsonContent.gallery[i].phone + "</span>\n";
                        finalResponse += "        </a></address>\n";
                        //finalResponse += "        <p class=\"description\"><a href=\"" + url + qsClick + "\" target=\"_blank\" onclick=\"objectEventTracker._trackEvent('Click','" + jsonContent.gallery[i].name + "');\">" + jsonContent.gallery[i].description + "</a></p>\n";
                        if (jsonContent.gallery[i].work != "") { finalResponse += "        <p class=\"work\"><a href=\"" + url + qsClick + "\" target=\"_blank\" onclick=\"objectEventTracker._trackEvent('Click','" + jsonContent.gallery[i].name + "');\"><span class=\"label\">Featured work:</span><br />" + jsonContent.gallery[i].work + "</a></p>\n"; }
                        if (jsonContent.gallery[i].artist != " ") { finalResponse += "        <p class=\"artist\"><a href=\"" + url + qsClick + "\" target=\"_blank\" onclick=\"objectEventTracker._trackEvent('Click','" + jsonContent.gallery[i].name + "');\"><span class=\"label\">By</span> " + jsonContent.gallery[i].artist + "</a></p>\n"; }
                        finalResponse += "        <p class=\"refer_aa\">When calling, please refer to Art & Antiques/" + strCurrentMonth + "</p>\n";
                        finalResponse += "    </div>\n";
                        finalResponse += "    <a href=\"" + url + qsClick + "\"" + alignImage + " target=\"_blank\" onclick=\"objectEventTracker._trackEvent('Click','" + jsonContent.gallery[i].name + "');\"><img src=\"" + jsonContent.gallery[i].image + "\" alt=\"" + jsonContent.gallery[i].work + ", by" + jsonContent.gallery[i].artist + "\" /></a>\n";
                        finalResponse += "</div>\n";
                        y++;
                    }
                }
                n++;
            }
        }
    }



    // show paging if there's more than one page and Looping is false.
    if ((n > nPageSize) && (!bLoopGalleries)) {

        // determine the number of pages.  Round 
        var nPages = n / nPageSize;
        if ((n / nPageSize) > Math.round(nPages)) { nPages = Math.round(nPages) + 1; }

        pagingResponse += "<div class=\"PageNumbers\" style=\"margin-top:0px;\">";
        if (nPage > 0) { pagingResponse += "<a href=\"\" onclick=\"rewriteGalleries(document.aspnetForm.country.value,document.aspnetForm.state.value,document.aspnetForm.city.value,document.aspnetForm.txt.value,4," + (nPage - 1) + ");return false;\">&lt;prev</a> | "; }
        for (x = 0; x < nPages; x++) {
            if (x == nPage) {
                pagingResponse += "<b>" + (x + 1) + "</b> | ";
            }
            else {
                pagingResponse += "<a href=\"\" onclick=\"rewriteGalleries(document.aspnetForm.country.value,document.aspnetForm.state.value,document.aspnetForm.city.value,document.aspnetForm.txt.value,4," + x + ");return false;\">" + (x + 1) + "</a> | ";
            }
        }
        if (nPage + 1 < nPages) { pagingResponse += "<a href=\"\" onclick=\"rewriteGalleries(document.aspnetForm.country.value,document.aspnetForm.state.value,document.aspnetForm.city.value,document.aspnetForm.txt.value,4," + (nPage + 1) + ");return false;\">next&gt;</a>"; }
        pagingResponse += "</div>";
    }
    else {
        finalResponse = "<div style=\"border-bottom: solid 1px; #404040\"></div>" + finalResponse
    }

    if (bLoopGalleries)
    { document.getElementById(objGalleriesContainer).innerHTML += finalResponse; }
    else {
        if (n > 0)
        { document.getElementById(objGalleriesContainer).innerHTML = pagingResponse + finalResponse + pagingResponse; }
        else
        { document.getElementById(objGalleriesContainer).innerHTML = finalResponse + "<p>No Galleries Were Found</p>" }
    }
}

function processGalleries(originalRequest) {

    // Get JSON values 
    var jsonRaw = originalRequest.responseText;

    // Eval JSON response into variable 
    jsonContent = eval("(" + jsonRaw + ")");

    if (bLoopGalleries) {
        rewriteGalleries("", "", "", "", 0, 0);

        if (arrGallery.length > 1) {
            // start looping through the galleries
            playGalleries();
        }
    }
    else {
        buildCountries();
        rewriteGalleries("", "", "", "", 4, 0);
    }
}

function initGalleries(element, loop) {
    bLoopGalleries = loop; // make the loop variable global, it's used more in processGalleries and rewriteGalleries
    objGalleriesContainer = element; // make the container element global
    //new Ajax.Request("js/galleries.json", {method: 'get',onComplete: processGalleries}) // run the AJAX command and pro
    //new Ajax.Request("/Featured-Galleries/galleries.js", {method: 'get',onComplete: processGalleries})
    new Ajax.Request("Handlers/FeaturedAdvertiserList.ashx", { method: 'get', onComplete: processGalleries })
}

function playGalleries() {
    //loop through the lead articles and hide them
    for (i = 0; i <= arrGallery.length - 1; i++) {
        document.getElementById(arrGallery[i]).style.display = "none";
    }

    //set the first gallery to display
    nClickedGalleryLink = Math.floor(Math.random() * arrGallery.length);

    //initiate the change
    changeGallery();
}

// change the article
function changeGallery() {
    // set the previous article to the last current
    var nPreviousGallery = nCurrentGallery;

    // if a change has been initated outside of time
    if (nClickedGalleryLink >= 0) {
        clearTimeout(); // clear the timer
        nCurrentGallery = nClickedGalleryLink; // set the current to the selected
        nClickedGalleryLink = -1; // clear out the selected for next time
    }
    else {
        if (nCurrentGallery != arrGallery.length - 1) // determine if we reached the end
        { nCurrentGallery = nCurrentGallery + 1; } // if not continue to the next article
        else
        { nCurrentGallery = 0; } // or move to the first article
    }

    fadeOut(nPreviousGallery); // fade out the previous gallery
    fadeIn(nCurrentGallery); // fade in the current gallery

    timerArticleLeads = setTimeout("changeGallery()", 10000); // initate the time to change automatically
}

// fade out
function fadeOut(gallery) {
    // retrieve the article's div
    var object = document.getElementById(arrGallery[gallery]).style;

    // test if the article is completely faded
    if (nFadeOutOpacity > 0) {
        // set the opacity levels for the different browsers
        object.opacity = (nFadeOutOpacity / 100);
        object.MozOpacity = (nFadeOutOpacity / 100);
        object.KhtmlOpacity = (nFadeOutOpacity / 100);
        object.filter = "alpha(opacity=" + nFadeOutOpacity + ")";

        nFadeOutOpacity = nFadeOutOpacity - 5; // set the next fade out level
        setTimeout("fadeOut(" + gallery + ")", 50); // continue the fade out
    }
    else {
        object.display = "none"; // completely hide the div
        nFadeOutOpacity = 100; // reset the opacity for the next fade out
    }
}

// fade in
function fadeIn(gallery) {
    // retrieve the article's div
    var object = document.getElementById(arrGallery[gallery]).style;

    // set it to visible
    object.display = "block";

    // test if the article is completely visible
    if (nFadeInOpacity < 100) {
        // set the opacity levels for the different browsers
        object.opacity = (nFadeInOpacity / 100);
        object.MozOpacity = (nFadeInOpacity / 100);
        object.KhtmlOpacity = (nFadeInOpacity / 100);
        object.filter = "alpha(opacity=" + nFadeInOpacity + ")";

        nFadeInOpacity = nFadeInOpacity + 5; // set the next fade in level
        setTimeout("fadeIn(" + gallery + ")", 50); // continue the fade in
    }
    else {
        //
        new Ajax.Request(arrGalleryImpressionUrl[gallery], { method: 'get' }); // Track the impression
        //pageTracker._trackPageview(window.escape("/Featured-Galleries/Impressions/" + )); // and on Google Analytics
        //objectEventTracker._trackEvent("Impression", arrGalleryName[gallery]);
        //

        nFadeInOpacity = 0; // reset the opacity for the next fade in
    }
}