/* ////////////////////////////////////////////////////////////////////////////////////////////////////

// core.js should only be used for functions that are site-wide
// separate functions that are page specific into page specific javascript files
// camelCase should be used for all variable and function names, e.g. "initLinks()" NOT "init_links()"

//////////////////////////////////////////////////////////////////////////////////////////////////// */

var drawer;
var drawerButton;

function init()
{
    drawer = $('#searchDrawer');
    drawerButton = $('#searchDrawer a.drawerButton');
    if($('body').hasClass('home'))
    {
        setTimeout(closeDrawer,2000);
    }
    drawerButton.bind('click',function(){
        var pos = parseInt(drawer.css('top').replace('px',''));
        if(pos < 0)
            openDrawer();
        else
            closeDrawer();
    });
    $('#searchDrawer a#drawer-close').bind('click', closeDrawer);

    $(window).resize(centerModals);
    
    $('#screen, .close-modals').bind('click',closeModals);
    
    $('input.watermark, textarea.watermark').bind('focus',clearContent).bind('blur',replenishContent);
    
    setLinks();
    
    if(isIE6())
        pngFix();

}

function clearContent()
{
    var d = $(this).attr('default');
    if($(this).val() == d)
        $(this).val('');
}

function replenishContent()
{
    var d = $(this).attr('default');
    if($(this).val() == '')
        $(this).val(d);
}

function openDrawer()
{
    drawer.stop(true).animate({top:0},500,function(){drawerButton.children('img').attr('src',drawerButton.children('img').attr('src').replace('down','up'));});
}

function closeDrawer()
{
    drawer.stop(true).animate({top:-68},500,function(){drawerButton.children('img').attr('src',drawerButton.children('img').attr('src').replace('up','down'));});
}



function pngFix() {
    $('img[src$=png], img[src$=png$]').each(function() {
        var src = $(this).attr("src");
        var width = $(this).outerWidth();
        var height = $(this).outerHeight();
        $(this).attr("src", "/assets/images/x.gif");
        $(this).css({ 'background-image': 'none', 'height': height, 'width': width });
        $(this).css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '",sizingMethod="scale")');
    });
}

function isIE6() {
    return ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined));
}

function getKeyCode(e) {
    return window.event ? e.keyCode : e.which;
}

function onHitKey(e, keyCode, elementOrId) {
    if (getKeyCode(e) == keyCode) {
        var type = typeof elementOrId;

        var element = (type.toLowerCase() == "object") ? elementOrId : document.getElementById(elementOrId);

        if (element.click != null) {
            element.click();
        }
        else if (element.onclick != null) {
            element.onclick();
        }
        else if (element.href != null && element.href.match('javascript:')) {
            eval(unescape(element.href.replace('javascript:', '')));
        }

        return false;
    }
    else {
        return true;
    }
}

//map functions
function resumeMap(id) {
    setActiveSearchResult($(id));
    if ($('#directions:visible').length > 0) {
        $('#directions').hide();
        $('#directions_map').hide();
        $('#map').css('width', '900px');
        $('#map div[id$=ctlGoogleMap]').show().css('width', 'auto');
    }
    return false;
}

function setActiveSearchResult(clickObj) {
    clearActiveSearchResult();
    clickObj.parents('li').addClass('active');
}

function clearActiveSearchResult() {
    $('.locationsList li').removeClass('active');
}

function initStoreLocator() {
    $('.searchResults .getDirections').click(function() {
        setActiveSearchResult($(this));
        /*var lnk = $(this).find('.org a');
        lnk.click();*/
    });

}

//modals
function openModal(key)
{
    var target;
    switch (key) {
        case 'share':
            target = $('#emailModal');
        break;
        case 'send':
            target = $('#phoneModal');
        break;
        case 'compare':
            target = $('#compareModal');
        break;
        case 'comparefew':
            target = $('#compareModalFew');
        break;
        default:
            target = $('');
        break;
    }
    
    if(target != '')
    {
        showScreen();
        target.css('opacity','0').show();
        target.stop(true).animate({opacity:1},400)
    }
}
function openStoreModal(key, storeId) {
    var target;
    switch (key) {
        case 'share':
            target = $('#emailModal');
            break;
        case 'send':
            target = $('#phoneModal');
            break;
        case 'compare':
            target = $('#compareModal');
            break;
        case 'comparefew':
            target = $('#compareModalFew');
            break;
        default:
            target = $('');
            break;
    }

    if (target != '') {
        showScreen();

        target.find(".storeid").val(storeId);
        target.css('opacity', '0').show();
        target.stop(true).animate({ opacity: 1 }, 400)
    }
}
function centerModals()
{
    var w = $(window).width();
    var h = $(window).height();
    var s = $(document).scrollTop();
    var tw;
    var th;
    
    if($('.modal.positioned:visible').length > 0)
    {
        hideScreen();
        closeModals();
    }
    else
    {
        $('.modal').not('.positioned').each(function() {
            tw = $(this).outerWidth();
            th = $(this).outerHeight();

            $(this).css({ 'top': ((h - th) / 2) + s, 'left': (w - tw) / 2 });
        });
        
        $('#screen').height($(document).height());
    }
}

function showScreen()
{
    centerModals();
    $('#screen').css('opacity','0').show();
    $('#screen').stop(true).animate({opacity:0.75},400);
}

function hideScreen()
{
    $('#screen').stop(true).animate({opacity:0},400,function(){$(this).hide()});
}

function closeModals()
{
    $('.modal').stop(true).animate({opacity:0},400,function(){$(this).hide()});
    hideScreen();
}

//rel external popups
function popUp(url)
{
    var newwindow = window.open(url, 'extWin', 'height=800,width=1024,scrollbars=1,resizable=1,menubar=1,status=1,toolbar=1,location=1,personalbar=1');
    if (newwindow.focus) {
        newwindow.focus();
    }
    return false;
}

function setLinks()
{
    var anchors = document.getElementsByTagName('a');
    for (var i = 0; i < anchors.length; i++) {
        var h = anchors[i].getAttribute('href');
        var r = anchors[i].getAttribute("rel");
        if (h != null && r != null) {
            if (r.match('external')) {
				//popup script
				anchors[i].onclick = function() {
					return popUp(this.getAttribute("href"));
				};
				anchors[i].setAttribute("title", (anchors[i].getAttribute("title") != null ? anchors[i].getAttribute("title") + " - " : "") + anchors[i]);
            }
        }
    }
}

function printScreen() {
    window.print();
    return false;
}

//compare class
var compareFootwear;
function setupCompare() {
	compareFootwear = new compareClass('__REDWING_COMPARISON_PRODUCTS', 'ul.products');
	compareFootwear.init();
}

function clearCompare() {
	compareFootwear.clear();
}

function compareClass(cookieName, group) {
    var _this = this;
    this._cookieVal = '';
    this._productCount = 0;
    this._cookieCompareType = '';
    this._currentCompareCookie = cookieName;
    this._selector = group;
	this._chkcompare = _this._selector + ' input.chkcompare';

	this.init = function() {
	    if (readCookie(_this._currentCompareCookie) != null) {
	        _this._cookieVal = readCookie(_this._currentCompareCookie);
	        _this._productCount = _this._cookieVal.split(',').length;
	        $('body').append($('#compareModalFew, #compareModal'));
	    }

	    // check that at least two items are being compared
	    $('a.compareTop').click(function(e) {
	        if (_this._productCount < 2) {

	            var cf = $('#compareModalFew');
	            var l = $(this).offset().left + 15;
	            var t = $(this).offset().top - cf.outerHeight() + 75;

	            openModal('comparefew');

	            cf.css({ 'left': l + 'px', 'top': t + 'px' });
	            _this.setupButtons();

	            return false;
	        }
	        return;
	    });
	    
	    $(_this._selector + ' a.compare').click(function(e) {
	        if (_this._productCount < 2) {

	            var cf = $('#compareModalFew');
	            var l = $(this).offset().left + 5;
	            var t = $(this).offset().top - cf.outerHeight() - 5;

	            openModal('comparefew');

	            cf.css({ 'left': l + 'px', 'top': t + 'px' });
	            _this.setupButtons();

	            return false;
	        }
	        return;
	    });

	    // on click for checkbox compare
	    $(_this._chkcompare).click(function(e) {
	        // increase productCount if checked
	        if ($(this).attr('checked') != false) {
	            ++_this._productCount;
	            _this.buildCompareLink($(this));
	        } else {
	            // decrease product count if unchecked
	            --_this._productCount;
	            _this.removeCompareLink($(this));
	        }

	        // if productCount is greater than 3 show warning
	        if (_this._productCount > 3) {
	            $(this).attr('checked', '');
	            _this.removeCompareLink($(this));
	            --_this._productCount;

	            var cf = $('#compareModal');
	            var l = $(this).offset().left + 15;
	            var t = $(this).offset().top - cf.outerHeight() - 5;

	            openModal('compare');

	            cf.css({ 'left': l, 'top': t });
	            _this.setupButtons();
	        } else {
	            //else toggle product on
	            _this.toggleProduct($(this).attr('checked'), $(this).attr('value'));
	        }
	    });

	    // check all compare boxes that have a cookie value
	    var currCompItems = '';
	    $(_this._chkcompare).each(function(i) {
	        var chkcompareVal = $(this);
	        if (_this._cookieVal.indexOf(chkcompareVal.attr('value')) != -1) {
	            chkcompareVal.attr('checked', 'checked');
	        }
	    });

	    // build each compare link
	    $(_this._selector + ' a.compare').each(function(i) {
	        var compItems = $(this).attr('href') + _this._cookieVal.split(',');
	        $(this).attr('href', compItems);
	    });
	    return;
	};

    this.buildCompareLink = function(check) {
        var compItems =  $(_this._selector + ' a.compare').attr('href') + "," + check.val();
        compItems = compItems.replace("/,", '/');
        $(_this._selector + ' a.compare, #compareModal #btnCompare').attr('href', compItems);
    };    

    this.removeCompareLink = function(check) {
        var compItems = $(_this._selector + ' a.compare').attr('href');
        compItems = compItems.replace(check.val(), '');
        compItems = compItems.replace(",,", ",");
        compItems = compItems.replace(/,$/g, '');//removing trailing commas
        compItems = compItems.replace("/,", '/');//removing leading commas
        
        $(_this._selector + ' a.compare, #compareModal #btnCompare').attr('href', compItems);
    };
	
	this.setupButtons = function() {
		//close btns
		var closeBtn = '#compareModal #btnClose, #compareModalFew #btnReturn';
		$(closeBtn).click(function(e) {
			_this.closeWarning();
			return false;
		});
		
		//compare btns
		var compareBtn = '#compareModal #btnCompare';
		$(compareBtn).click(function(e) {
			_this.compare();
			return true;
		});
		
		//clear all btns
		var clearAllBtn = '#compareModal #btnClearAll';
		$(clearAllBtn).click(function(e) {
			_this.clear();
			_this.closeWarning();
			return false;
		});
	}

    this.clear = function() {
        _this._productCount = 0;
        $(_this._chkcompare + ':checked').each(function(e){
            $(this).removeAttr('checked');
            _this.removeCompareLink($(this));
        });
        _this._cookieVal = '';
        eraseCookie(_this._currentCompareCookie);
    };

    this.toggleProduct = function(checked, prod_id) {
        if (_this._cookieVal.indexOf(prod_id) == -1) {
            _this._cookieVal += ',' + prod_id;
        } else {
			var cookieArr = _this._cookieVal.split(',');
			var newArr = $.grep(cookieArr, function(n) {
				return (n != prod_id);
			});
			
			_this._cookieVal = newArr.join(',');
        }
        _this.compare();
    };

    this.compare = function() {
        if (_this._cookieVal.indexOf(',') == 0) {
            _this._cookieVal = _this._cookieVal.substr(1);
        }
		eraseCookie(_this._currentCompareCookie);
        createCookie(_this._currentCompareCookie, _this._cookieVal);
    };

    this.closeWarning = function() {
        closeModals();
    };

}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

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) {
	createCookie(name,"",-1);
}

//search validation
function validateZip(btn) {
    var obj = $(btn).prev('input:text');
    var zip = $(obj).val();
    var regex = /[a-zA-Z0-9\s]{5,7}$/;
    var valid = zip.match(regex);
    if(valid == null)
        $(obj).addClass('error');
    else
    {
        $('#searchDrawer input, #searchDrawer select, #storeLocatorSearch input, #storeLocatorSearch select').removeClass('error');
        window.location = "/red-wing-shoe-stores/" + zip;
    }
    //return valid != null;
    return false;
}

function validateCityState() {
    var city = $(".drwCity").val();
    var state = $(".drwSelect").val();
    
    if (city.length == 0) {
        $(".drwCity").addClass('error');
        
    }
    
    if (state == '----') {
        $(".drwSelect").addClass('error');
        
    }
    
    if ((city.length != 0) && (state != '----')) {
        $(".drwCity").removeClass('error');
        $(".drwSelect").removeClass('error');
        
        window.location = "/red-wing-shoe-stores/" + (city != '' ? city : '') + (city != '' && state != '' ? ', ' : '') + (state != '' ? state : '');
        
    }
    return false;
  
}


function validateCity(btn) {
    var cityobj = $(btn).siblings('input:text:last');
    if(cityobj.length == 0)
        cityobj = $(btn).parent().prev().children('input:text');
    
   
    
    var city = $(cityobj).val();

    var stateobj = $(btn).prev('select');
    var state = $(stateobj).children('option:selected').val();
    
    var valid = city != '' || state != '';
    if(!valid)
    {
        $(cityobj).attr('class', city == '' ? 'error' :'');
        $(stateobj).attr('class', state == '' ? 'error' : '');
    }
    else
    {
        $('#searchDrawer input, #searchDrawer select, #storeLocatorSearch input, #storeLocatorSearch select').removeClass('error');
        window.location = "/red-wing-shoe-stores/" + (city != '' ? city : '') + (city != '' && state != '' ? ', ' : '') + (state != '' ? state : '');
    }
    //return valid;
    return false;
}

$(document).ready(init);

