var RecaptchaOptions = {
    theme : 'custom',
    custom_theme_widget: 'recaptcha_widget'
};

var toolTipBG = new Image();
toolTipBG.src = '_style/_images/bubble.png';

function openMOOdalBox(url) {
	MOOdalBox.open( // case matters
    	url+"", // the link URL
    	"Details", // the caption (link's title) - can be blank
    	"wizard" // width and height of the box - can be left blank
	);
}

function initPrintComponents(){
    $$('.print-action').each(function(element) {
        element.addEvent('click', function(event) {
            this.target = "print-"+this.id;
            $("print-"+this.id).style.border = 'none';
            $("print-"+this.id).style.display = '';
        });
        
    });
}

function initToolTips(elements) {
    if (elements == null) {
        elements = $$('.toolTips');
    }
    var Tips2 = new Tips(elements, {
        initialize:function(){
            this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 0, wait: false}).set(0);
        },
        onShow: function(toolTip) {
            this.fx.start(1);
        },
        onHide: function(toolTip) {
            
            this.fx.start(0);
        },
        offsets: {'x': 25, 'y': -40}
    });
}

function toggleRedMoonTab(panelId, tab) {
    
    //init
    $$('.mootabs_title a').each(function (tabElement) {
        if (tabElement.hasClass('active')) {
            tabElement.removeClass('active');
        }
    });
    $$('.mootabs_panel').each(function (panel) {
        if (panel.hasClass('active')) {
            panel.removeClass('active');
        }
        panel.setStyle('display', 'none');
    });
    
    //toggle
    if (!tab.hasClass('active')) {
        tab.addClass('active');
    }
    if ($(panelId) != null && !$(panelId).hasClass('active')) {
        $(panelId).addClass('active');
        $(panelId).setStyle('display', 'block');
    }
}


function initRedMoonTabs() {
    if ($('redmoon-tabs') != null) {
        $$('.mootabs_title a').each(function (tabElement) {
            var tabElementREL = tabElement.getAttribute('rel');
            
            if (tabElementREL.indexOf('tab#') == 0 && tabElementREL.length > 4) {
                var panelId = tabElementREL.substring(4, tabElementREL.length);

                tabElement.addEvent('click', function () { 
                    toggleRedMoonTab(panelId, tabElement); 
                });
                if (tabElement.hasClass('active')) {
                    toggleRedMoonTab(panelId, tabElement);
                }
            }
        });
    }
}

function isInteger( string ) {
    return !isNaN( parseInt( string ) );
}
function confirmDelete(element) {
    return confirm("Are you sure you want to delete: " + element.title + "?");
}

function togglePetFoodCreatorHelpStart() {
    $$('a.pet-food-creator-start-help-togglable').each(function(togglable) { 
        if (togglable.getStyle('display') == 'none') {
            togglable.setStyle('display', '');
        } else {
            togglable.setStyle('display', 'none');
        }
    });
}

var flashingArrow = null;
function flashArrow(numFlashesRemaining) {
    flashingArrow.removeClass('selected');
    numFlashesRemaining--;
    if (numFlashesRemaining == 0) {
        flashingArrow.addClass('selected');
    } else {
        window.setTimeout('startFlashArrow(null,' + numFlashesRemaining + ')', 250);
    }
}

function startFlashArrow(arrow, numFlashes) {
    if (arrow != null) {
        flashingArrow = arrow;
    }
    
    if (numFlashes > 0 && !flashingArrow.hasClass('selected')) {
        flashingArrow.addClass('selected');
        window.setTimeout('flashArrow(' + numFlashes + ')', 500);
    }
}

function initRedMoonFlashingArrows(isFirst) {
    var count = 3;
    
    $$('a.arrow').each(function(arrow) {
        
        if (count > 0) {    
            var triggered = false;
        }
        $$('.' + arrow.getAttribute('id') + '-trigger-off').each(function(trigger){
            
            if (count > 0) {
                //for the pet food name field/trigger
                if (trigger.hasClass('special-arrow-trigger-off')) {
                    if (trigger.value.length > 0 && trigger.value.length <= 26) {
                        triggered = true;
                    }
                    
                } else {
                    if (trigger.checked == 1) {
                        triggered = true;
                    }
                }
            }

            if (isFirst == true) {
                trigger.addEvent('change', function(event) {
                    arrow.addClass('selected');
                    initRedMoonFlashingArrows(false);
                });
            }
        });
        
        if (count > 0) {    
            if (!triggered) {
                count = 0;
                startFlashArrow(arrow, 10);
            } else {
                arrow.addClass('selected');
            }
        }
        
        count--;
    });
}
var messagingIntervals = 10;
function initFlashingSuccessMessage() {
    if (messagingIntervals > 0) {
        var swapped = false;
        
        $$('.success-inverse').each(function(element){
            element.removeClass('success-inverse');
            element.addClass('success');
            swapped = true;
        });
        if (swapped == false) {
            $$('.success').each(function(element){
                element.removeClass('success');
                element.addClass('success-inverse');
            });
        }
    }
    
    messagingIntervals--;
    window.setTimeout('initFlashingSuccessMessage()', 750);
}
function initFlashingErrorMessage() {
    if (messagingIntervals > 0) {
        var swapped = false;
        $$('.error').each(function(element){
            element.removeClass('error');
            element.addClass('error-inverse');
            swapped = true;
        });
        
        if (swapped == false) {
            $$('.error-inverse').each(function(element){
                element.removeClass('error-inverse');
                element.addClass('error');
            });
        }
    }
    
    messagingIntervals--;
    window.setTimeout('initFlashingErrorMessage()', 750);
}
function initFlashingWarningMessage() {
    if (messagingIntervals > 0) {
        var swapped = false;
        $$('.warning').each(function(element){
            element.removeClass('warning');
            element.addClass('warning-inverse');
            swapped = true;
        });
        
        if (swapped == false) {
            $$('.warning-inverse').each(function(element){
                element.removeClass('warning-inverse');
                element.addClass('warning');
            });
        }
    }
    
    messagingIntervals--;
    window.setTimeout('initFlashingWarningMessage()', 750);
}
function initExternalLinkTracking() {
	//pageTracker._trackEvent('External Link', 'PDF', '/salesForms/orderForm1.pdf');
    var hostname = window.location.hostname;
    hostname = hostname.replace("www.","").toLowerCase();
    var anchors = document.getElementsByTagName("a"); 
    for (var i=anchors.length-1; i>=0; i--) {
        var anchor = anchors[i];
        var href = anchor.href.toLowerCase();
        if(href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) {
			anchor.addEvent('click', function(event) {
                _gaq.push(['_trackEvent', 'External Link', 'Visit', this+'']);
            });
		}              
    };

}

function trackExternalLink(element) {
    _gaq.push(['_trackEvent', 'External Link', 'Visit', element+'']);
}
function loadRexRSSFeed() {
	google.load("feeds", "1");

    function initialize() {
      var feed = new google.feeds.Feed("http://rextalkingdog.com/feed/");
      feed.load(function(result) {
        if (!result.error) {
            var html = "";               
            var feed = result.feed;
            //alert(feed.toSource());
            html += '<div class="entries">';
            for (i = 0; i <result.feed.entries.length; i++) {
              var entry = result.feed.entries[i];
            
              html += '<div class="entryTitle"><a href="' + entry.link + '">' + entry.title + '</a> - <span class="publishDate">' + entry.publishedDate + '</span></div>';
              html += '<div class="entryText">' + entry.contentSnippet + '</div>';
              html += '<div class="readMore"><a onclick="trackExternalLink(this);" href="' + entry.link + '" target="_blank">Read More &raquo;</a></div>';
              break;
            }
            if (document.getElementById("feedControl") != null) {
                document.getElementById("feedControl").innerHTML = html;
            }
        }
      });
    }
    google.setOnLoadCallback(initialize);
}
var fmaRotationFXDuration = 1000;
var fmaRotationTimeIncrement = 7500;
var fmaRotationIndex = 0;
var fmaRotationMaxIndex = 4;
var fmaSelectionMade = null;
function rotateFMA(recursing) {
    
    if (fmaSelectionMade == null) {
        if ($$('#home-fma-browser a').length - 1 <= fmaRotationMaxIndex) {
            fmaRotationMaxIndex = $$('#home-fma-browser a').length - 1;
        }
        
        $$('#home-fma-browser a').each(function(toggler, togglerIndex){
            if (togglerIndex != fmaRotationIndex && toggler.hasClass('selected')) {
                toggler.removeClass('selected');
            }
            else 
                if (!toggler.hasClass('selected') && togglerIndex == fmaRotationIndex) {
                    toggler.addClass('selected');
                }
        });
            
        if (recursing) {
            $$('#home-fma .home-fma-slide').each(function(pane, paneIndex){
                if (paneIndex == fmaRotationIndex) {
                    
                    var ffbFX = new Fx.Styles(pane, {
                        duration: fmaRotationFXDuration,
                        wait: false
                    });
                    ffbFX.start({
                        'opacity': 1
                    });
                } else {
                    
                    var ffbFX = new Fx.Styles(pane, {
                        duration: fmaRotationFXDuration,
                        wait: false
                    });
                    
                    ffbFX.start({
                        'opacity': 0
                    });
                }
            });
        }
        if (fmaRotationIndex < fmaRotationMaxIndex) {
            //increment
            fmaRotationIndex++;
        } else {
            //reset
            fmaRotationIndex = 0;
        }
        window.setTimeout('rotateFMA(true)', fmaRotationTimeIncrement);
    }
}
function initFMABrowser() {
    try {
        
    /* intoria added */   
		$$('#youtubeVideo').addEvent('click', function(event) {
			ev = new Event(event);
			ev.stop();
		});
		/* end, intoria added */
				
        $$('#home-fma-browser a').each(function(element, elementIndex) {
            
            element.addEvent('click', function(event) {
                ev = new Event(event);
                ev.stop();
                
                fmaRotationIndex = elementIndex;
                
                $$('#home-fma-browser a').each(function(toggler) {
                    if (toggler.hasClass('selected')) {
                        toggler.removeClass('selected');
                    }
                });
                
                if (!element.hasClass('selected')) {
                    $$('#home-fma .home-fma-slide').each (function (pane, paneIndex) {
                        if (paneIndex == fmaRotationIndex) {
                            var ffbFX = new Fx.Styles(pane, {
                                duration: fmaRotationFXDuration,
                                wait: false
                            });
                            ffbFX.start({
                                'opacity': 1
                            });
                        } else {
                            
                            var ffbFX = new Fx.Styles(pane, {
                                duration: fmaRotationFXDuration,
                                wait: false
                            });
                            
                            ffbFX.start({
                                'opacity': 0
                            });
                        }
                    });
                    
                    element.addClass('selected');
                }
                
                fmaSelectionMade = elementIndex;
                return false;
            });
            
            if (element.hasClass('selected')) {
                fmaSelectionMade = elementIndex;
            }
        });
        
        $$('#home-fma .home-fma-slide').each (function (pane, paneIndex) {
            pane.setStyle('display', '');
            pane.setStyle('position', 'absolute');
            
            if (fmaRotationIndex == paneIndex) {
                pane.setStyle('opacity', '1');
            } else {
                pane.setStyle('opacity', '0');
            }
        });
        
        rotateFMA(false);
    } catch(e) {
        window.setTimeout('initFMABrowser()', 500);
    }
}
function openNewsletterSubscriptionForm(form) {
	// setup the email address field
	new Ajax(form.action+ "?controller=PCContact&action=setupNewsletterEmail&newsletter-signup-email="+form.elements['newsletter-signup-email'].value, {
        method: 'get',
		onComplete: function(){
			MOOdalBox.open( // case matters
		        form.action+"", // the link URL
		        "Newsletter Signup Form", // the caption (link's title) - can be blank
		        "external" // width and height of the box - can be left blank
		    );
		}
    }).request();
	return false;
}

function initWeeklyRankingsPanel() {
    $$('.weekly-ranking-pane').each(function(pane) {
        if (!pane.hasClass('selected')) {
            pane.setStyle('display', 'none');
        } else {
            pane.addClass('selected');
            pane.setStyle('display', '');
        }
    });
    $$('a.weekly-ranking-pane-toggler').each(function(toggler) {
        toggler.addEvent('click', function(event) {
            ev = new Event(event);
            ev.stop();
             
            $$('a.weekly-ranking-pane-toggler').each(function(togglerSibling, i) {
                if (togglerSibling.hasClass('selected')) {
                    togglerSibling.removeClass('selected');
                }
            });
            $$('.weekly-ranking-pane').each(function(paneSibling, i) {
                if (paneSibling.hasClass('selected')) {
                    paneSibling.removeClass('selected');
                    paneSibling.setStyle('display', 'none');
                }
            });
            
            
            this.addClass('selected');
            $('weekly-ranking-pane-' + this.getAttribute('id').substring(8, this.getAttribute('id').length)).addClass('selected');
            $('weekly-ranking-pane-' + this.getAttribute('id').substring(8, this.getAttribute('id').length)).setStyle('display', '');
        });
    });
}

window.addEvent('domready', function() {
    initFMABrowser();
    if(document.all && navigator.appVersion.indexOf("MSIE")>-1 && navigator.appVersion.indexOf("Windows")>-1) {
        var a = document.getElementsByTagName("label");
        for(var i=0,j=a.length;i<j;i++){
          if(a[i].hasChildNodes && a[i].childNodes.item(0).tagName == "IMG")
          {
            a[i].childNodes.item(0).forid = a[i].htmlFor;
            a[i].childNodes.item(0).onclick = function(){
              var e = document.getElementById(this.forid);
              switch(e.type){
                case "radio": e.checked|=1;break;
                case "checkbox": e.checked=!e.checked;break;
                case "text": case "password": case "textarea": e.focus(); break;
              }
            }
          }
        }
      }

    $$('.on-clear-action').each(function (element) {
        element.addEvent('click', function(event) {
            switch (this.getAttribute('id')) {
                case 'header-login-email-address': {
                    if (this.getAttribute('value') == 'email@address.com') {
                        this.setAttribute('value', '');
                    }
                    break;
                }
                case 'header-login-password': {
                    if (this.getAttribute('value') == 'password') {
                        this.setAttribute('value', '');
                    }
                    break;
                }
                case 'petfood-name-1':
                case 'petfood-name': {
                    if (this.getAttribute('value') == 'Click here and Enter a name for your food...') {
                        this.setAttribute('value', '');
                    } else if (this.getAttribute('value') == 'CLICK here and ENTER a name for your food...') {
                        this.setAttribute('value', '');
                    }
                    break;
                }
				case 'pet-name': {
                    if (this.getAttribute('value') == 'SEARCH FOR PET') {
                        this.setAttribute('value', '');
                    }
                    break;
                }
            }
            })
        });
    
    $$('.popup-calendar').each(function (element) {
        Calendar.setup(
        {
            inputField : element.getAttribute('id'), // ID of the input field
            ifFormat : "%Y-%m-%d", // the date format
            button : element.getAttribute('id'), // ID of the button
            singleClick : true
        }
      );
    });
    //MOOdalBox.init.bind(MOOdalBox);    
    initToolTips(); 
    
    window.setTimeout('initRedMoonTabs()', 250);
    
    
    initPrintComponents();
    
    $$('.ff-phone-part').each(function (element, fieldIncrement) {
        //alert(fieldIncrement);
        element.addEvent('keyup', function (event) {
            if (fieldIncrement < 2) {
                if (element.value.length >= 3) {
                    $$('.ff-phone-part')[fieldIncrement+1].focus();
                }
            }
        });
    });
    
    initRedMoonFlashingArrows(true);
    if ($$('.success').length > 0) {
        initFlashingSuccessMessage();
    }
    if ($$('.error').length > 0) {
        initFlashingErrorMessage();
    }
	if ($$('.warning').length > 0) {
        initFlashingWarningMessage();
    }
    window.setTimeout('initWeeklyRankingsPanel()', 250);
    
	initExternalLinkTracking();
});

