var activeTabID;
var activeTab;
var activeHoverTab;

/* Clears input value on blur */
$(document).ready(function() {

  /* Sets default values on form elements */
    $('.DefaultValue').each(function() {
        if (!this.disabled) {
            this.focus();
            this.blur();
        }
    });
    
    
	$('.default-value').each(function() {
		var default_value = this.value;
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
			}
		});
    });
});


    
    function DefaultValue(field, defaulttext) {
    if (field.disabled) {
        return;
    }
    changeInputType(field, "text", defaulttext, false, true);
}

function ExistsInArray(array, value) {
    var len = array.length;
    for (var i = 0; i < len; i++) {
        if (array[i] == value) {
            return true;
        }
    }
    return false;
}


    
 var passwordFields = [];   
    //oldElm - a reference to the input element
//iType - value of the type property: 'text' or 'password'
//iValue - the default value, set to 'password' in the demo
//blankValue - true if the value should be empty, false otherwise
//noFocus - set to true if the element should not be given focus
function changeInputType(oldElm, iType, iValue, blankValue, noFocus) {
    if (oldElm.type == "password") {
        if (!ExistsInArray(passwordFields, oldElm.id)) {
            passwordFields.push(oldElm.id);
        }
    }

    if (!oldElm || !oldElm.parentNode || (iType.length < 4) || !document.getElementById || !document.createElement) {
        return;
    }

    var isMSIE = /*@cc_on!@*/false; //http://dean.edwards.name/weblog/2007/03/sniff/
    if (!isMSIE) {
        var newElm = document.createElement('input');
        newElm.type = iType;
    } else {
        var newElm = document.createElement('span');
        newElm.innerHTML = '<input type="' + iType + '" name="' + oldElm.name + '">';
        newElm = newElm.firstChild;
    }

    var props = ['name', 'id', 'className', 'size', 'tabIndex', 'accessKey', 'autocomplete', 'onkeypress'];
    for (var i = 0, l = props.length; i < l; i++) {
        if (oldElm[props[i]]) {
            newElm[props[i]] = oldElm[props[i]];
        }
    }

    var existingclass = oldElm["className"];
    existingclass = existingclass.replace("DefaultValue entered", "");
    existingclass = existingclass.replace("DefaultValue", "");
    existingclass = existingclass.trim();

    if (oldElm["value"] == "" && oldElm["value"] != iValue) {
        newElm["className"] = existingclass + " DefaultValue";
    } else {
        newElm["className"] = existingclass + " DefaultValue entered";
    }

    newElm.onfocus = function() {
        return function() {
            if (this.hasFocus) {
                return;
            }

            var type = "text";
            //Check and see if this is a password field
            if (ExistsInArray(passwordFields, oldElm.id)) {
                type = "password";
            }

            var newElm = changeInputType(this, type, iValue, (this.value.toLowerCase() == iValue.toLowerCase()) ? true : false);
            if (newElm) {
                newElm.hasFocus = true;
            }
        }
    } ();
    
    newElm.onblur = function() {
        return function() {
            if (this.hasFocus) {
                if (this.value == '' || (this.value.toLowerCase() == iValue.toLowerCase())) {
                    changeInputType(this, 'text', iValue, false, true);
                }
            }
        }
    } ();
    
    //hasFocus is to prevent a loop where onfocus is triggered over and over again
    newElm.hasFocus = false;
    //Some browsers need the value set before the element is added to the page
    //while others need it set after
    if (!blankValue) {
        if (oldElm["value"] == "") {
            newElm.value = iValue;
        } else {
            newElm.value = oldElm["value"];
        }
    }
    oldElm.parentNode.replaceChild(newElm, oldElm);
    if (!isMSIE && !blankValue) {
        if (oldElm["value"] == "") {
            newElm.value = iValue;
        } else {
            newElm.value = oldElm["value"];
        }
    }
    if (!noFocus || typeof (noFocus) == 'undefined') {
        window.tempElm = newElm;
        setTimeout("tempElm.hasFocus=true;tempElm.focus();", 1);
    }
    return newElm;
}


// Controls main navigation
$(function() {
    try {
        $("ul#main_nav li").hover(function() {
            $(this).addClass("active");
            $('ul:first', this).css('display', 'block');
            if ($(this).attr("id") != "" && $(this).attr("id") != activeTabID) {
                $(activeTab).removeClass("active");
            }
        }, function() {
            $(this).removeClass("active");
            $('ul:first', this).css('display', 'none');
            if (($(this).attr("id") != "" && $(this).attr("id") != activeTabID) || $(this).attr("id") == activeTabID) {
                $(activeTab).addClass("active");
            }
        });
    }
    catch (ex) { }
});

//Set the active class in the navigation based on the URL
$(function() {
    try {
        $("#left_nav_top").find('*[href="' + window.location.pathname + '"]').addClass("active");
        $("#footer").find('*[href="' + window.location.pathname + '"]').addClass("active");
    }
    catch(ex) {}
});

function HideContent(d) {
	document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
	document.getElementById(d).style.display = "block";
}

function formatFBTime(fbDate) {
    var arrDateTime = fbDate.split("T");
    var arrDateCode = arrDateTime[0].split("-");
    var strTimeCode = arrDateTime[1].substring(0, arrDateTime[1].indexOf("+"));
    var arrTimeCode = strTimeCode.split(":");
    var valid_date = new Date()
    valid_date.setUTCFullYear(arrDateCode[0]);
    valid_date.setUTCMonth(arrDateCode[1] - 1);
    valid_date.setUTCDate(arrDateCode[2]);
    valid_date.setUTCHours(arrTimeCode[0]);
    valid_date.setUTCMinutes(arrTimeCode[1]);
    valid_date.setUTCSeconds(arrTimeCode[2]);
    return valid_date;
}

/* Homepage Rotator */

window.onerror = function(desc, page, line, chr) {
    /* alert('JavaScript error occurred! \n'
    +'\nError description: \t'+desc
    +'\nPage address:      \t'+page
    +'\nLine number:       \t'+line
    );*/
}

$(function() {
    $('a').focus(function() { this.blur(); });
    SI.Files.stylizeAll();
    slider.init();

    $('input.text-default').each(function() {
        $(this).attr('default', $(this).val());
    }).focus(function() {
        if ($(this).val() == $(this).attr('default'))
            $(this).val('');
    }).blur(function() {
        if ($(this).val() == '')
            $(this).val($(this).attr('default'));
    });

    $('input.text,textarea.text').focus(function() {
        $(this).addClass('textfocus');
    }).blur(function() {
        $(this).removeClass('textfocus');
    });

    var popopenobj = 0, popopenaobj = null;
    $('a.popup').click(function() {
        var pid = $(this).attr('rel').split('|')[0], _os = parseInt($(this).attr('rel').split('|')[1]);
        var pobj = $('#' + pid);
        if (!pobj.length)
            return false;
        if (typeof popopenobj == 'object' && popopenobj.attr('id') != pid) {
            popopenobj.hide(50);
            $(popopenaobj).parent().removeClass(popopenobj.attr('id').split('-')[1] + '-open');
            popopenobj = null;
        }
        return false;
    });
    $('p.images img').click(function() {
        var newbg = $(this).attr('src').split('bg/bg')[1].split('-thumb')[0];
        $(document.body).css('backgroundImage', 'url(' + _siteRoot + 'images/bg/bg' + newbg + '.jpg)');

        $(this).parent().find('img').removeClass('on');
        $(this).addClass('on');
        return false;
    });
    /*$(window).load(function() {
        $.each(css_ims, function() { (new Image()).src = _siteRoot + 'css/images/' + this; });
        $.each(css_cims, function() {
            var css_im = this;
            $.each(['blue', 'purple', 'pink', 'red', 'grey', 'green', 'yellow', 'orange'], function() {
                (new Image()).src = _siteRoot + 'css/' + this + '/' + css_im;
            });
        });
    });*/
    $('div.sc-large div.img:has(div.tml)').each(function() {
        $('div.tml', this).hide();
        $(this).append('<a href="#" class="tml_open">&nbsp;</a>').find('a').css({
            left: parseInt($(this).offset().left) + 864, top: parseInt($(this).offset().top) + 1
        }).click(function() {
            $(this).siblings('div.tml').slideToggle();
            return false;
        }).focus(function() { this.blur(); });
    });
});
var slider = {
    num: -1,
    cur: 0,
    cr: [],
    al: null,
    at: 10 * 700,
    ar: true,
    init: function() {
        if (!slider.data || !slider.data.length)
            return false;

        var d = slider.data;
        slider.num = d.length;
        var pos = Math.floor(Math.random() * 1); //slider.num);
        for (var i = 0; i < slider.num; i++) {
            $('#' + d[i].id).css({ left: ((i - pos) * 1000) });
            $('#slide-nav').append('<a id="slide-link-' + i + '" href="#" onclick="slider.slide(' + i + ');return false;" onfocus="this.blur();">' + (i + 1) + '</a>');
        }

        $('img,div#slide-controls', $('div#slide-holder')).fadeIn();
        slider.text(d[pos]);
        slider.on(pos);
        slider.cur = pos;
        window.setTimeout('slider.auto();', slider.at);
    },
    auto: function() {
        if (!slider.ar)
            return false;

        var next = slider.cur + 1;
        if (next >= slider.num) next = 0;
        slider.slide(next);
    },
    slide: function(pos) {
        if (pos < 0 || pos >= slider.num || pos == slider.cur)
            return;

        window.clearTimeout(slider.al);
        slider.al = window.setTimeout('slider.auto();', slider.at);

        var d = slider.data;
        for (var i = 0; i < slider.num; i++)
            $('#' + d[i].id).stop().animate({ left: ((i - pos) * 1000) }, 1000, 'swing');

        slider.on(pos);
        slider.text(d[pos]);
        slider.cur = pos;
    },
    on: function(pos) {
        $('#slide-nav a').removeClass('on');
        $('#slide-nav a#slide-link-' + pos).addClass('on');
    },
    text: function(di) {
        slider.cr['a'] = di.client;
        slider.cr['b'] = di.desc;
        slider.ticker('#slide-client span', di.client, 0, 'a');
        slider.ticker('#slide-desc', di.desc, 0, 'b');
    },
    ticker: function(el, text, pos, unique) {
        if (slider.cr[unique] != text)
            return false;

        ctext = text.substring(0, pos) + (pos % 2 ? '-' : '_');
        $(el).html(ctext);

        if (pos == text.length)
            $(el).html(text);
        else
            window.setTimeout('slider.ticker("' + el + '","' + text + '",' + (pos + 1) + ',"' + unique + '");', 30);
    }
};
// STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if (!window.SI) { var SI = {}; };
SI.Files = {
    htmlClass: 'SI-FILES-STYLIZED',
    fileClass: 'file',
    wrapClass: 'cabinet',

    fini: false,
    able: false,
    init: function() {
        this.fini = true;
    },
    stylize: function(elem) {
        if (!this.fini) { this.init(); };
        if (!this.able) { return; };

        elem.parentNode.file = elem;
        elem.parentNode.onmousemove = function(e) {
            if (typeof e == 'undefined') e = window.event;
            if (typeof e.pageY == 'undefined' && typeof e.clientX == 'number' && document.documentElement) {
                e.pageX = e.clientX + document.documentElement.scrollLeft;
                e.pageY = e.clientY + document.documentElement.scrollTop;
            };
            var ox = oy = 0;
            var elem = this;
            if (elem.offsetParent) {
                ox = elem.offsetLeft;
                oy = elem.offsetTop;
                while (elem = elem.offsetParent) {
                    ox += elem.offsetLeft;
                    oy += elem.offsetTop;
                };
            };
        };
    },
    stylizeAll: function() {
        if (!this.fini) { this.init(); };
        if (!this.able) { return; };
    }
};

function postBackOnEnter(e, UniqueButtonID) {
    if (window.event) { e = window.event; }
    if (e.keyCode == 13) {
        __doPostBack(UniqueButtonID, "");
    }
    return (e.keyCode != 13);
}

/* Rating Star Functionality */
var starHover = false;
function starmousein(star) {
    starHover = true;
    var starData = star.id.split("_");
    var currentRecipeID = parseInt(starData[0]);
    var currentRating = parseInt(starData[1]);
    var currentHoverStar = parseInt(starData[2]);
    for (var i = 1; i <= currentHoverStar; i++) {
        var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
        changestar.setAttribute("src", "/images/gold-star.gif");
    }
    var fillerStart = currentHoverStar + 1;
    for (var i = fillerStart; i <= 5; i++) {
        var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
        changestar.setAttribute("src", "/images/empty-star.gif");
    }
}
function starmouseout(star, rating) {
    starHover = false;
    setTimeout(function() { startmouseout_callback(star, rating) }, 100);
}
function startmouseout_callback(star, rating) {
    if (starHover == false) {
        var starData = star.id.split("_");
        var currentRecipeID = parseInt(starData[0]);
        var currentRating = parseInt(starData[1]);
        var currentHoverStar = parseInt(starData[2]);
        for (var i = 1; i <= currentRating; i++) {
            var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
            changestar.setAttribute("src", "/images/star.gif");
        }
        for (var i = currentRating + 1; i <= 5; i++) {
            var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
            changestar.setAttribute("src", "/images/empty-star.gif");
        }
    }
}

function checkEmail(address) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(address)) {
        return true;
    }
    return false;
}
