// $Id: site.js 2161 2008-07-08 13:59:12Z ade $

/* ***************************************************** */
/* Form processing
/* ***************************************************** */


function checkEditForm(formId, required_id) {
    
    if (!required_id) required_id = 'required';
    if ($j('#' + required_id).length) {
        
        // Remove any messages if they exist
        clearError(required_id);
        clearMessage();

        // Get the required fields
        var reqFields = $(required_id).value.split(',');
                
        var badFields = 0;

        // Iterate over each required field
        $j.each( reqFields, function(idx, reqField) {
            
            // If the field is something like foo|bar, make sure one or the other is supplied
            if (reqField.match(/\|/)) {
                
                var state = 0;
                
                // Get the real field names
                var fieldNames = reqField.split('|');
                var invalid = [];
                
                // Iterate over each field and check
                fieldNames.each( function(fieldName) {
                    if (checkField(fieldName)) {
                        invalid.push(fieldName);
                    }
                    else {
                        state++;
                    }
                });
                
                // If state is > 0, then we found at least one valid field
                if (! state) {
                    invalid.each( function(field) {
                        highlightField(field, 1);
                    });
                    badFields++;
                }
            }
            else {
                
                // Check for field values
                var state = checkField(reqField);
                
                // If state > 0 then we found a bad field
                badFields += state;
                
                // Highlight if it's bad
                if (state) {
                    highlightField(reqField, state);
                }
            }
        });
        
        if (badFields) {
            displayError(formId, 'Please fill in a value for all required fields');
            return false;
        }
    }
    
    return true;
}

function checkField(name) {
    
    var state = 0;
    
    var field = $j('#' + name);
    if (! field.length) return 0;
    
    switch (field.get(0).type.toLowerCase()) {
        case 'text':
        case 'password':
        case 'textarea':
        case 'file':                    
            var state = field.val() == '' ? 1 : 0;
            break;
                                    
        case 'select-one':
            state = field.val() == '' ? 1 : 0;
            break;
            
        case 'select-multiple':
            state = 1;
			$j('#' + name + ' :selected').each(function(i, selected){ 
				if($j(selected).val() != '') {
					state = 0; 
				}
			});
            break;
            
        case 'radio':
        	var state = 1;
        	//I'm not certain this is the optimal jquery way to handle this situation.... but it worked so I'm happy for now
        	var input_name = $j('#' + name).get(0).name;
        	if ($j('input:radio[name=' + input_name  + ']:checked').length) {
        		state = 0;
        	}
        	break;
        case 'checkbox':   
            var state = 1;
            //Not sure why this first version didn't work.  jquery is still an odd beast to me....
            //if($j('#' + name + ' :checked').length) {
            if ($j('#' + name).get(0).checked) {
				state = 0;
            }
            break;
    }
    
    return state;
}

function highlightField(name, on) {
    
    var field = $(name);
    if (! field) return;
    
    // Set the field background color
    if (on) field.addClassName('error');
    else field.removeClassName('error');
    
    // Get all the labels in the document
    var labels = document.getElementsByTagName('label');
    $A(labels).each( function(label) {
        
        // Set the label color if the label is for the specified field
        var labelFor = label.getAttributeNode('for'); 
        if (labelFor && labelFor.value == name) {
            label.style.color = on ? 'red' : '';
        }
    });
}

function getTinyMCEValue(id) {
    
    var value = $F(id);
    tinyMCE.selectedInstance = tinyMCE.getInstanceById(id);
    if (tinyMCE.selectedInstance) {
        value = tinyMCE._cleanupHTML(tinyMCE.selectedInstance, tinyMCE.selectedInstance.getDoc(), tinyMCE.settings, tinyMCE.selectedInstance.getBody(), false, true);
    }
    
    return value;
}

function checkAll(formId, field, val) {
    
    var form;
    if (form = $(formId)) {        
        if (form.elements[field].length) {
            $A(form.elements[field]).each( function(checkbox) {
                if (!checkbox.disabled)
                    checkbox.checked = val;
            });
        }
        else {
            if (!form.elements[field].disabled)
                form.elements[field].checked = !form.elements[field].checked;
        }
    }
}

//This is used to hide and show grey 'Search' text in search box
function changeSearchValue (id, newValue)
{
    formElement = document.getElementById(id);
    if(formElement.value == '') {
        formElement.value = newValue;
        formElement.className = 'grey searchField';
    } else if(formElement.value == 'Search') {
        formElement.value = newValue;
        formElement.className = 'searchField';
    }
}

//This removes the default 'Search' text when there are no
//user-inputted search terms
function checkSearchTerm (id)
{
    formElement = document.getElementById(id);
    if(formElement.value == 'Search' && formElement.className == 'grey searchField') {
        formElement.value = '';
    }
}
/* ***************************************************** */
/* Errors and messages
/* ***************************************************** */

function clearError(required) {
    
    if (required == '') required = 'required';
    
    if ($(required)) {

        // Get the required fields
        var reqFields = $(required).value.split(',');
        
		// Iterate over each required field
        $j.each(reqFields, function(idx, reqField) {
            highlightField(reqField, 0);
        });
    }
    
    // Remove the error message if one exists
    var error;
    if (error = $('checkFormError')) {
        error.parentNode.removeChild(error);
    }
}

function displayError(id, message) {
    
    var obj;
    if (obj = $(id)) {
        
        error = document.createElement('div');
        error.className = 'error';
        error.style.fontWeight = 'bold';
        error.id = 'checkFormError';
        error.innerHTML = message;
        
        obj.parentNode.insertBefore(error, obj);
        
        Element.scrollTo(error);
    }
}

function clearMessage() {
    
    var message;
    if (message = $('formMessage')) {
        message.parentNode.removeChild(message);
    }
}

function displayMessage(text) {
            
    // Remove the message if one exists
    clearMessage();
        
    var editForm;
    if (editForm = $('editForm')) {
        
        message = document.createElement('div');
        message.className = 'message';
        message.id = 'formMessage';
        messageText = document.createTextNode(text);
        message.appendChild(messageText);
        
        body = document.getElementsByTagName('body');
        if (body.length) {                
            body[0].insertBefore(message, editForm);
        }
    }
    
    window.scrollTo(0,0);
}

/* ***************************************************** */
/* Misc
/* ***************************************************** */

function cookietest() {
    
    var date = new Date();
    var cookiestr = 'TEST' + date.getTime();
    document.cookie = "cookietest=" + cookiestr + "; path=/";
    if (document.cookie.indexOf(cookiestr, 0) < 0) {
        Element.show('noCookies');
    }
}

function noCacheParam() {
    var now = new Date();
    return '&r=' + now.getTime();
}

function ajaxFailure(request) {
    alert('An error was encountered: ' + request.responseText);
}

function jsonParse(request) {
    
    // Parse the JSON response
    var res = JSON.parse(request.responseText);
    if (!res) {
        ajaxFailure(request);
        return false;
    }
    
    // Convert to a hash
    res = $H(res);
    
    return res;
}

/* ***************************************************** */
/* Contact Form
/* ***************************************************** */

function checkContactForm(form, email) {
    
    // Do basic checks
    if (! checkEditForm(form, 'required')) {
        return false;
    }
    
    // Make sure the email address is valid
    if (! $F(email).match(/.+\@.+\..+/)) {
        clearError();
        highlightField(email, 1);
        displayError(form, 'You must supply a valid email address');
        return false;
    }
    
    return true;
}

/* ***************************************************** */
/* Top Nav
/* ***************************************************** */
//No longer in use

// Event.observe(window,'load',function() {

    // if ($('siteheadernavcontainer')) {

        // // Find all top-level category links
        // $$('#siteheadernavcontainer li a').each( function(el) {
        
            // // Add onmouseover event
            // Event.observe(el, 'mouseover', function() {        
            
                // // Remove "current" class from top-level categories
                // $$('#siteheadernavcontainer li a').invoke('removeClassName', 'current');
                
                // // Hide the 2nd-level category
                // $$('.siteheadersubnavcontainer').invoke('hide');
                
                // // Only activate the 2nd-level category if it's women, men, etc.
                // if (el.id) {            
                
                    // // Add "current" class
                    // el.addClassName('current');
                    
                    // // Show the appropriate 2nd-level category links
                    // var category = el.id.split('-');
                    // $('siteheadersubnavcontainer-'+category[1]).show();
                // }
            // });
        // });
        
// /*        Event.observe('searchandtitlecontainer', 'mouseover', function() {        
            
                // // Remove "current" class from top-level categories
                // $$('#siteheadernavcontainer li a').invoke('removeClassName', 'current');
                
                // // Hide the 2nd-level category
                // $$('.siteheadersubnavcontainer').invoke('hide');
        // });*/
    // }    
// });
    
/* ***************************************************** */
/* Other Nav
/* ***************************************************** */

function toggleNav(id) {
    
    var menu = $(id);
    if (!menu) return;
    
    menu.className = (menu.className == 'sd-nav-open') ? 'sd-nav-closed' : 'sd-nav-open';
    if (menu.className == 'sd-nav-open') {
        $$('.sd-nav-open').each( function(el) {
            if (el.id != menu.id)
                el.className = 'sd-nav-closed';
        });
    }
}


/* ***************************************************** */
/* Bubblenav & top nav
/* ***************************************************** */
	 /*
			Initialize and render the Menu when its elements are ready 
			to be scripted.
	 */
	 
	 YAHOO.util.Event.onContentReady("bubblenavmenu", function () {
	 
		  /*
				 Instantiate a Menu:  The first argument passed to the 
				 constructor is the id of the element in the page 
				 representing the Menu; the second is an object literal 
				 of configuration properties.
		  */
	 
		  var oMenu = new YAHOO.widget.Menu("bubblenavmenu", 
            {
                position: "static", 
                hidedelay: 750,
                lazyload: true,
					 shadow: false,
					 effect: { 
                    effect: YAHOO.widget.ContainerEffect.FADE,
                    duration: 0.25
                }
            }
        );
	 
		  /*
				 Call the "render" method with no arguments since the 
				 markup for this Menu instance is already exists in the page.
		  */
		  oMenu.cfg.setProperty("keepopen", true);
		  oMenu.render();
		  
	 });

	YAHOO.util.Event.onContentReady("categorymenu", function () {
		  /*
		  Instantiate a MenuBar:  The first argument passed to the 
		  constructor is the id of the element in the page 
		  representing the MenuBar; the second is an object literal 
		  of configuration properties.
		  */
		  var oMenuBar = new YAHOO.widget.MenuBar("categorymenu",
				{
					 position: "static",
					 shadow:false,
					 autosubmenudisplay: true, 
					 hidedelay: 750, 
					 lazyload: true,
					 effect: { 
						  effect: YAHOO.widget.ContainerEffect.FADE,
						  duration: 0.25
					 }
				}
		  );
			
			
		  /*
		  Call the "render" method with no arguments since the 
		  markup for this MenuBar instance is already exists in 
		  the page.
		  */
			
		  oMenuBar.render();
       
		  
	 });
	 

/* ***************************************************** */
/* Scroller
/* ***************************************************** */

function SDScroller() {};
SDScroller.prototype = {

    initialize: function(options) {
    
        var leftButton = $j('#featuremorebuttonleft');
        var rightButton = $j('#featuremorebuttonright');
        var autoScrollLink = $j('#autoScroll');
        var containerSlider = $j('#containerslider');
        
        this.boxWidth = 150;
        this.visibleBoxes = 5;
        
        var target = this;
        // Event.observe(leftButton,'click',function() { this.moveRight() }.bind(this));
        leftButton.click(function() {
			target.moveRight();
		});
        rightButton.click(function() {
			target.moveLeft();
		});
		// Event.observe(rightButton,'click',function() { this.moveLeft() }.bind(this));
		containerSlider.hover(
			function() {
				target.clrScroll();
			},
			function() {
				target.moveLeft(1);
			}
		);
        // Event.observe(containerSlider,'mouseover', function() { this.clrScroll() }.bind(this));
        // Event.observe(containerSlider,'mouseout', function() { this.moveLeft(1) }.bind(this));
        
    },
    
    clrScroll: function() {
        if(typeof curr_scroll!= 'undefined') {
            clearTimeout(curr_scroll);
        }        
    },
    
    moveLeft: function(auto) {
        /*
         * TO DO: calculate where slides are, due to autoScroll
         * set moveLeft & moveRight to move forward or back an
         * adjusted amount so that movement ends on full slide,
         * instead of cutting off partial slide.
         */

        
        this.clrScroll();
        var slider = $j('#containerslider'); 
        var itemCount = $j('#containerslider a').length;
        var limit = (itemCount - this.visibleBoxes) * this.boxWidth * -1;
        
        // go ahead and re-set the slider length, just in case
        slider.css( { width: ((itemCount + 4) * this.boxWidth) + 'px' } );
        
        var marginStyle = slider.css('left');
        var marginArray = marginStyle.split('px');
        var currentMargin = parseInt(marginArray[0]);

        // five images per slide
        newMargin = currentMargin - (this.boxWidth * this.visibleBoxes);
        
        //account for autoscroll, so we don't end up in the middle of a slide
        marginOffset = Math.abs(currentMargin) % (this.boxWidth);
        if(marginOffset) {
            newMargin += marginOffset;
        }
        if (newMargin < limit)
            newMargin = limit;
        
        
        if(auto) {
            this.autoSlide(currentMargin,currentMargin,limit);
        } else {
            this.animateSlide(currentMargin,currentMargin,newMargin);
        }
    },
    
    moveRight: function(auto) {
        
        this.clrScroll();
        var slider = $j('#containerslider');
        var limit = 0;
        
        var marginStyle = slider.css('left');
        var marginArray = marginStyle.split('px');
        var currentMargin = parseInt(marginArray[0]);

        // five images per slide
        newMargin = currentMargin + (this.boxWidth * this.visibleBoxes);
        
        //account for autoscroll, so we don't end up in the middle of a slide
        marginOffset = Math.abs(currentMargin) % (this.boxWidth);
        if(marginOffset) {
            newMargin += marginOffset;
        }
        
        if (newMargin > limit)
            newMargin = limit;
            
        if(auto) {
            this.autoSlide(currentMargin,currentMargin,limit);
        } else {
            this.animateSlide(currentMargin,currentMargin,newMargin);
        }
        
    },
    
    animateSlide: function(current,start,end,auto) {
    
        var increment = 50;
        var interval = 30;

        var slider = $j('#containerslider');
        
        if (start > end) {
            
            current -= increment;
            
            if (current <= end)
                current = end;
                
        } else {
        
            current += increment;
            
            if (current >= end)
                current = end;
        }
        
        
        slider.css( { left:current + 'px' } );
        
        var target = this;
        
        if (current != end) {
        
            animate = function() { target.animateSlide(current,start,end,auto) };
            curr_scroll = setTimeout(animate,interval);
        } else if(auto) {
            restart = function() { target.moveLeft(1) };
            setTimeout(restart, 1000);
        }
    },
    
    autoSlide: function(current,start,end) {
    
        var increment = 1;
        var interval = 50;

        var slider = $j('#containerslider');
        
        if (start > end) {
            
            current -= increment;
            
            if (current <= end)
                current = end;
                
        } else {
        
            current += increment;
            
            if (current >= end)
                current = end;
        }
        
        
        slider.css( { left:current + 'px' } );
        
        var target = this;
        
        if (current != end) {
            animate = function() { target.autoSlide(current,start,end) };
            curr_scroll = setTimeout(animate,interval);
        } else {
            rewind = function() { target.reset(1) };
            setTimeout(rewind, 1000);
        }
    },
    
    reset: function(auto) {

        this.clrScroll();
        var slider = $('containerslider');
        var limit = 0;
        
        var marginStyle = slider.getStyle('left');
        var marginArray = marginStyle.split('px');
        var currentMargin = parseInt(marginArray[0]);
        
        if(auto) {
            this.animateSlide(currentMargin,currentMargin,0,1);
        } else {
            this.animateSlide(currentMargin,currentMargin,0);
        }
    }
}

function switchScroller(toID) {
    
    $category = $F('featureCategory');
    
    var url = 'scroller/view/' + toID + ($category > 0 ? '/' + $category : '');

    if(toID == 'new') {
        view_all_url = 'site/search' + ($category > 0 ? '?category=' + $category : '');
    } else {
        view_all_url = 'site/search?context=featured' + ($category > 0 ? '&category=' + $category : '');;
    }
    
    $('view_all_scrollnav').setAttribute('href', view_all_url);
    
    new Ajax.Updater('containerslider',url,
    {
        parameters: { ajax: 1 },
        onSuccess: function() {  $$('.tabnavigationcontainer .tableft').each( function(el) {  el.removeClassName('current'); }); $('tab_' + toID).addClassName('current'); resetScroller();setTimeout(autoScroll, 2000); }
    
    }); 
}

function resetScroller() {

    sdscroller.reset();
}

function autoScroll() {
    sdscroller.moveLeft(1);
}


function initRedButtons() {

    // get rid of any redButton values
    $j('.redButton').each( function() { $j(this).attr('title', $j(this).val()); $j(this).val(''); });
}

var sdscroller;

$j(document).ready(function() {
    
    initRedButtons();
    
    if ($j('#containerslider').length) {
        sdscroller = new SDScroller();
		sdscroller.initialize( { } );
        autoScroll();
    }
});

function baseURL() {

    // Get the URL from the BASE tag
    var base = $j('base');
    var url = base.length ? base[0].href : '';

    return url;
}

