//////////////////////////////////////////////////////////////////////
// add a page load event
//////////////////////////////////////////////////////////////////////
// Add it to window.onload event
//addOnLoad(function() {clearfix("clearthis");});

/*
* Adds a function into the onload event
* Usage: addOnLoad(functionName)
* Or, if you need to pass arguments in the
* function:
* addOnLoad(function() {functionName("argument")})
*/
function addOnLoad(newFunction) {
    var currentOnLoad = window.onload;
    if (typeof window.onload != "function") {
        window.onload = newFunction;
    }
    else {
        window.onload = function() {
            currentOnLoad();
            newFunction();
        }
    }
}




//////////////////////////////////////////////////////////////////////
// cookie functions
//////////////////////////////////////////////////////////////////////
function createCookie(name, value, days, domain) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    wholecookie = name + "=" + value + expires + "; path=/;";
    if (domain) { wholecookie = wholecookie + "domain=" + domain + ";"; }
    document.cookie = wholecookie;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name, domain) {
    createCookie(name, "", -1, domain);
}

//////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////
// find x and y positions of an element
//////////////////////////////////////////////////////////////////////
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}
//////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////
// scrollPageTo(endPosition)
//////////////////////////////////////////////////////////////////////
var scrolldelay;
function scrollPageTo(end) {
    clearTimeout(scrolldelay); // clear the repeater
    var currentPos = (document.all) ? document.body.scrollTop : window.pageYOffset;
    if (currentPos > end) {
        window.scrollBy(0, -10); // horizontal and vertical scroll increments
        scrolldelay = setTimeout('scrollPageTo(\'' + end + '\')', 10);
    }
    //alert(end);
}



//////////////////////////////////////////////////////////////////////
// upperFirst(whattomakeuppercasefirst)
// makes things all lowercase then uppercases the first letter of
// each word
//////////////////////////////////////////////////////////////////////
function upperFirst(u) {
    u = u.toLowerCase();
    u = u.split(' ');
    for (i = 0; i < u.length; i++)
        u[i] = u[i].replace(/^(.)/, u[i].charAt(0).toUpperCase());
    return u.join(' ');
}
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// make me a window
//////////////////////////////////////////////////////////////////////

function makewindow(url, name, wi, hi, scroll) {
    if (!scroll) { scroll = 0; }
    mywin = window.open(url, name, 'width=' + wi + ',height=' + hi + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll);
}

//////////////////////////////////////////////////////////////////////
// autotab
//////////////////////////////////////////////////////////////////////
var phone_field_length = 0;
function TabNext(obj, event, len, next_field) {
    if (event == "down") {
        phone_field_length = obj.value.length;
    }
    else if (event == "up") {
        if (obj.value.length != phone_field_length) {
            phone_field_length = obj.value.length;
            if (phone_field_length == len) {
                next_field.focus();
            }
        }
    }
}


function makeDivLink(classname) {
    //newsitem
    //$$('div:empty');
    //a[rel]
    var myArray = $$('div.' + classname);
    var htmlvalue = "";

    for (var index = 0; index < myArray.length; ++index) {
        var elm = myArray[index];
        htmlvalue = htmlvalue + '<p>' + elm.type + '</p>'
    }
    //alert(myArray.length);
    $('linkmaker').innerHTML = htmlvalue;

}

//////////////////////////////////////////////////////////////////////

// assign click events to the newsitem on the HP

//////////////////////////////////////////////////////////////////////



function setupHeadlineEvents() {

    var sp = $$('.newsitem').each(function(e) {

        var inc = e.getElementsByTagName("a");

        e.setAttribute('link', inc[0].getAttribute('href'));

        e.onclick = function() { location.href = this.getAttribute('link'); }

        e.onmouseover = function() { this.className = "newsitemon"; }

        e.onmouseout = function() { this.className = "newsitem"; }

    });

}


function getBiggest() {
    var biggest = 0;
    $$('div.overviewContainer').each(function(e) {
        e.onmouseover = function() {
            e.className = 'overviewContainerActive';
        }
        e.onmouseout = function() {
            e.className = 'overviewContainer';
        }
        e.onclick = function() {
            location.href = e.getElementsByTagName("a")[0].getAttribute("href");
        }
        if (e.offsetHeight > biggest) { biggest = e.offsetHeight; }
    }
    );

    $$('div.overviewContainer').each(function(e) { e.style.height = biggest; });
}


//////////////////////////////////////////////////////////////////////
// Google Popup sign-up 
//////////////////////////////////////////////////////////////////////

var msg = "";

function validateForm() {

    $('divprogress').show();
    $('formitems').hide();


    msg = "";
    $('divResponse').update('');
    $('divResponse').hide();

    if ($('firstname').value.length == 0) {
        msg += 'First Name<br/>';
    }

    if ($('lastname').value.length == 0) {
        msg += 'Last Name<br/>';
    }

    if ($('password').value.length < 4) {
        msg += 'Valid password<br/>';
    }

    if (!validateEmail())
    { msg += "Valid email address"; }

    if (msg != '') {
        $('divResponse').show();
        $('divResponse').update('<p class=\"deprecated\"><strong>Please verify the following:</strong> <br>' + msg + '</p>');
        //new Effect.Highlight($('divResponse'), { startcolor: '#FF0000', endcolor: '#ffff99' });
        $('divprogress').hide();
        $('formitems').show();
        return false;
    }
    else {
        //alert('check acount data');
        checkAccount();
    }

}


function validateGoogleSignupForm() {

    $('divprogress').show();
    $('formitems').hide();
    //$('closer').hide();

    msg = "";
    $('divResponse').update('');
    $('divResponse').hide();

    if ($('firstname').value.length == 0) {
        msg += 'First Name<br/>';
    }

    if ($('lastname').value.length == 0) {
        msg += 'Last Name<br/>';
    }

    if ($('password').value.length < 4) {
        msg += 'Valid password<br/>';
    }

    if (!validateEmail())
    { msg += "Valid email address<br/>"; }

    var checkboxcount = 0;

    if ($('chbMMO').checked == true) {
        checkboxcount++;        
    }

    if ($('chbRecap').checked == true) {
        checkboxcount++;
    }

    if ($('chbOV').checked == true) {
        checkboxcount++;
    }

    if (checkboxcount == 0) { 
        msg += "Select an e-newsletter <br/>"
    }
       

    if (msg != '') {
        $('divResponse').show();
        $('divResponse').update('<p class=\"deprecated\"><strong>Please verify the following:</strong> <br>' + msg + '</p>');
        //new Effect.Highlight($('divResponse'), { startcolor: '#FF0000', endcolor: '#ffff99' });
        $('divprogress').hide();
        $('formitems').show();
        return false;
    }
    else {
        //alert('check acount data');
        checkAccount();
    }

}


function validateEmail() {
    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    str = $('emailaddress').value;
    if (!str.match(emailRegEx)) {
        return false;
    }
    return true;
}

function checkAccount() {

    var url = '/ajax/verifysub.aspx';
    var email = $('emailaddress').value;
    var pars = 'emailaddress=' + email + '&dt=' + Date();

    //alert(email);

    var ajaxCheckAccountRequest = new Ajax.Request(url, {
        method: 'put',
        parameters: pars,
        asynchronous: true,
        onComplete: function(request) {
            var results = request.responseText.toString();
            //alert('check acount data = ' + results);

            return showEmailCheckResponse(results);

        }
    });

}



function showEmailCheckResponse(emailresponse) {
    // Process HTTP response and update input form
    var emailaddress = '';
    var textMessage = emailresponse;

    emailaddress = $('emailaddress').value;

    //alert('show email check response = ' + textMessage);

    textMessage = (textMessage.toUpperCase()).strip();
    emailaddress = (emailaddress.toUpperCase()).strip();
    //alert(textMessage);
    //alert(emailaddress);

    if (textMessage == emailaddress) {

        //alert('show email check response - dup email address');
        //Need to complete order and send confirmation email for 'report53', Siebel ID maybe - 1-1TCIA3
        $('divResponse').update('');
        $('divResponse').hide();
        //alert("new subscriber");
        createSubscriber(true);

    }
    else {

        //alert('show email check response - get ready to create account');
        $('divResponse').update('');
        $('divResponse').hide();
        //alert("existing subscriber");
        createSubscriber(false);



    }

    //alert('done with email check, what now?');
}

function createSubscriber(exists) {
    //debugger
    //alert('creating subscriber');
    
    
    var sub = '';
    var url = '/ajax/subsetup.aspx';
    var email = $('emailaddress').value;
    var firstname = $('firstname').value;
    var lastname = $('lastname').value;
    var password = $('password').value;
    //var ezines = $('ezines')
    //var sourcecode = $('sourcecode').value;
    var contact = 0;



    //alert(sourcecode);
    if ($('allowcontact').checked) {
        contact = 1;
    }

    sub = '<subscriber firstname=\"' + firstname + '\" lastname=\"' + lastname + '\" password=\"' + password + '\" emailaddress=\"' + email + '\" allowcontact=\"' + contact + '\" exist=\"' + exists + '\">';

    $$('input[name="ezine"]').each(function(s) {  
                      if(s.checked)
                      {
                          sub += '<product name=\"' + s.value + '\" sourcecode=\"' + s.readAttribute('sourcecode') + '\" />';
                      }                      
                      });    
      
    
    sub += '</subscriber>'

    //alert(sub);

    var pars = 'sub=' + sub + '&dt=' + Date();
    //alert(pars);
    var ajaxCreateSubRequest = new Ajax.Request(url,
            {

                method: 'put',
                encoding: 'UTF-8',
                parameters: pars,
                asynchronous: true,
                onComplete: function(request) {

                    var results = request.responseText;
                    if (results.length > 0) {
                        var processresults = results.indexOf('created');
                        //alert('process results = ' + processresults);
                        if (processresults > 0) {
                            showEzineThankyou();
                        }
                        else {
                            showError();
                        }
                    }

                }
            }
             );
}



function showError() {
    $('divResponse').show();
    $('divResponse').update('<p class=\"deprecated\">You have already signed up for this promotion. If you have received this message in error, please contact customer service 1-800-327-8833. Thank You.</p>');
    $('divprogress').hide();
    $('closer').show();
    $('formitems').show();
}

function showThankyou() {    
    $('divResponse').show();
    $('divResponse').update('<p><br>Thank you for signing up for the members-only report.<br> Please check your email for instruction on viewing the members-only report.</p>');
    $('divprogress').hide();
    $('closer').show();
    createCookie('GoogleBlogPopup', 'signup', 365);
    
    //send confirmation
}


function showEzineThankyou() {
    $('divMessage').show();
    $('divMessage').update('<p><br><strong>"Thank You for your subscription to our email newsletters<br><br>You should receive an email shortly verifying your subscription."</p></strong>');    
    $('divprogress').hide();
    $('closer').show();
    createCookie('GoogleBlogPopup', 'signup', 365);
}

function closeSignupForm() {
    
    $('light').hide();
    $('fade').hide();
}

//////////////////////////////////////////////////////////////////////

function posFade() {

    $('fade').style.width = document.body.scrollWidth > document.body.offsetWidth ? document.body.scrollWidth : document.body.offsetWidth + 'px';

    $('fade').style.height = document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px';

    //alert(document.body.offsetHeight + " " + document.body.scrollHeight)

}




