/**
* DOM Utilies Object for handling basic DOM actions
* @author					Dave Shepard
* @version					1.0
* @required libraries:		JQuery 1.3.2 or later
* 
* Usage:
*     $(document).ready(function(){
*     		DOMUtilities.init();
*     });
*     
* Can be initialized via the init(); method to apply to entire <body> or
* a scope can be passed to limit the initialization to the child elements
* of a particular element. Individual methods can als be called and passed
* a scope.
*/
var DOMUtilities = {
    targetBlank: function(locality) {
        // XHTML 1.0 Strict work around for external links
        $(locality + ' a[rel*="external"]').attr("target", "_blank");
    },
    inputAutoClear: function(locality) {
        $(locality + ' input.clearField').focus(function() {
            $(this).addClass('hasValue');
            if (this.defaultValue == this.value) this.value = '';
        }).blur(function() {
            if (this.value == '') { this.value = this.defaultValue; $(this).removeClass('hasValue') } else { $(this).addClass('hasValue') };
        });
    },
    imgRollover: function(locality) {
        // Image roll-over setup
        $(locality + ' img.rollOver, ' + locality + ' input[type="image"].rollOver')
			.mouseover(function() {
			    if (this.src.indexOf("_i.") != -1) {
			        this.src = this.src.replace("_i.", "_o.");
			    }
			}).mouseout(function() {
			    if (this.src.indexOf("_o.") != -1) {
			        this.src = this.src.replace("_o.", "_i.");
			    }
			    if (this.src.indexOf("_a.")) {
			        this.src = this.src.replace("_a.", "_i.");
			    }
			}).filter("input").mousedown(function() {
			    this.src = this.src.replace("_o.", "_a.");
			}).mouseup(function() {
			    this.src = this.src.replace("_a.", "_i.");
			});
    },
    init: function(locality) {
        if (locality == null) {
            locality = "body";
        }
        this.targetBlank(locality);
        this.inputAutoClear(locality);
        this.imgRollover(locality);
    }
}


$(document).ready(function() {

    DOMUtilities.init();

    var sbDeck = $('dl#home_deck.slideDeck').slidedeck({ autoPlay: true,

        cycle: true,

        autoPlayInterval: 5000, // 5 seconds

        hideSpines: true,

        complete: function(deck) {
            $('.deckNav li').removeClass('active');
            $('.deckNav li#goToSlide_' + deck.current + '').addClass('active');

        }

    });

    $('#storyContainer').mouseenter(function() {
        sbDeck.pauseAutoPlay = true;
    });

    $('#storyContainer').mouseleave(function() {
        sbDeck.pauseAutoPlay = false;
    });

    $('.deckArrow').click(function(e) {
        e.preventDefault();
    });

    $('#story #deckLeft').click(function() {
        sbDeck.prev();
    });

    $('#story #deckRight').click(function() {
        sbDeck.next();
    });

    $('#story li.deckNav').click(function(event) {
        //remove the all classes of current
        $('#story .deckNav li').removeClass('active');
        //move to the correct slide
        sbDeck.goTo(event.target.id.split('_')[1]);
        //set the right tab to active
        $(this).addClass('active');
    });


    var twitterDeck = $('dl#twitter_feed.slideDeck').slidedeck({ autoPlay: true,

        cycle: true,

        autoPlayInterval: 5000, // 5 seconds

        hideSpines: true

    });

    $('#feed_nav_left').click(function() {
        twitterDeck.prev();
    });

    $('#feed_nav_right').click(function() {
        twitterDeck.next();
    });

    $('.skin-sanfordburnham a.btn_prevSlide').click(function(event) {
        event.preventDefault();
        $('.skin-sanfordburnham .slidedeck').slidedeck().prev();
    })
    $('.skin-sanfordburnham a.btn_nextSlide').click(function(event) {
        event.preventDefault();
        $('.skin-sanfordburnham .slidedeck').slidedeck().next();
    });

    if ($(".modal").length) {
        $(".modal").fancybox({
            'overlayColor': '#000',
            'autoDimensions': true
        });
    }

    if ($("a.viewLarge").length) {
        $('.viewLarge').each(function() {
            var smallImgPath = $(this).parents('div').find('img').attr('src');
            var largeImgPath = smallImgPath.substring(0, smallImgPath.length - 4) + '_large.jpg';
            $(".viewLarge").fancybox({
                'overlayColor': '#000',
                'autoDimensions': true,
                'href': largeImgPath
            });
        });
    }




    $('#globalNav #navItems a').click(function(e) {
        e.preventDefault();
        nav = $(this).attr("id");
        if ($(this).parent('li').hasClass('followLink')) {
            location.href = $(this).parent('li').find('a').attr('href');
        } else if ($(this).hasClass('active')) {
            $('.globalNavOptions').slideUp(500);
            $('#navHandle span').fadeOut(500);
            $('.globalNavOptions').removeClass('open');
            $('#globalNav a').removeClass('active');
            $('html').unbind('click');
        } else {
            if ($('.globalNavOptions').hasClass('open')) {
                $('html').unbind('click');
                $('#navHandle span').fadeOut(500);
                $('.globalNavOptions.open').slideUp(500, function() {
                    $('#' + nav + 'Options.globalNavOptions').addClass('open');
                    $('#globalNav a').removeClass('active');
                    $('a#' + nav + '').addClass('active');
                    $('#' + nav + 'Options.globalNavOptions').slideDown(500, function() {
                        $('#navHandle span').fadeIn(100);
                        $('html').click(
					function() {
					    if ($('.globalNavOptions').hasClass('open')) {
					        $('.globalNavOptions').slideUp(500);
					        $('#navHandle span').fadeOut(500);
					        $('.globalNavOptions').removeClass('open');
					        $('#globalNav a').removeClass('active');
					        $(this).unbind('click');
					    };
					});
                    });
                });
                $('.globalNavOptions').removeClass('open');

            } else {
                $('a#' + nav + '').addClass('active');
                $('#' + nav + 'Options.globalNavOptions').addClass('open');
                $('#' + nav + 'Options.globalNavOptions').slideDown(500, function() {
                    $('html').click(
					function() {
					    if ($('.globalNavOptions').hasClass('open')) {
					        $('.globalNavOptions').slideUp(500);
					        $('#navHandle span').fadeOut(500);
					        $('.globalNavOptions').removeClass('open');
					        $('#globalNav a').removeClass('active');
					        $(this).unbind('click');
					    };
					});
                    $('#navHandle span').fadeIn(100);
                });
            };
        };
    });

    $('#navHandle').click(function() {
        $('.globalNavOptions').slideUp(500);
        $('#navHandle span').fadeOut(500);
        $('.globalNavOptions').removeClass('open');
        $('#globalNav a').removeClass('active');
        $('html').unbind('click');
    });

    $('#globalNavOptions').click(function(e) {
        e.stopPropagation();
    });

    $('#navItems').click(function(e) {
        e.stopPropagation();
    });

    $('.sideTab a.btn').click(function(e) {
        e.preventDefault();
        if ($(this).hasClass('active')) {
            //do nothing

        } else {
            $('.sideTabContainer .sideOpen').fadeOut(200, function() {
                $('.sideTabContainer div').removeClass('sideOpen');
                $('.sideTab a.btn').removeClass('active');
                $('#' + e.target.id + '').addClass('active');
                $('#' + e.target.id.split('_')[1] + '').fadeIn(200, function() {
                    $('#' + e.target.id.split('_')[1] + '').addClass('sideOpen');
                });
            });
        };
    });


    //talent tabs
    $('#talent_tabs li').click(function(e) {
        e.preventDefault();
        if ($(this).attr("id") == "nav_find") {
            $("#tabs_search_ui").show();
        }
        else {
            $("#tabs_search_ui").hide();
        }
        if ($(this).hasClass('active')) {
            //do nothing

        } else {
            $('.directoryTabHolder .tabOpen').fadeOut(200, function() {
                $('.directoryTabHolder div').removeClass('tabOpen');
                $('#talent_tabs li').removeClass('active');
                $('#' + e.target.id + '').addClass('active');
                $('#tab_' + e.target.id.split('_')[1] + '').fadeIn(200, function() {
                    $('#tab_' + e.target.id.split('_')[1] + '').addClass('tabOpen');
                });
            });
        };
    });

    //shared resources tabs
    $('.tabLinks li a').click(function(e) {
        var self = $(this);
        e.preventDefault(); if ($(this).parent('li').hasClass('active')) {
            //do nothing

        } else {
            $('#shared_listings_container .tabOpen').hide();
            $('#shared_listings_container div').removeClass('tabOpen');
            $('.tabLinks li').removeClass('active');
            $(self).parent('li').addClass('active');
            $('#tab_' + e.target.id.split('_')[1] + '').show();
            $('#tab_' + e.target.id.split('_')[1] + '').addClass('tabOpen');
        };
    });

    $('#link_loader').html('');
    $('#feed_social_links a').mouseenter(function() {
        socialLink = $(this).attr('class');
        $('#feed_social_links_url li a.' + socialLink + '').fadeIn(200);


    })

    $('#feed_social_links a').mouseleave(function() {
        socialLink = $(this).attr('class');
        $('#feed_social_links_url li a.' + socialLink + '').hide();
    })

    //talent focus tab system
    $('#tabs_container li').click(function(e) {
        tabOpen = this.id.split('_')[1];
        tabClicked = this.id;
        if ($(this).hasClass('active')) {
            //do nothing
        } else {
            $('#tabs_container li').removeClass('active');
            $('#big_tab_container .open').hide();
            $('#big_tab_container .open').removeClass('open');
            $('#' + tabOpen + '_tab').show();
            $('#' + tabOpen + '_tab').addClass('open');
            $('#' + tabClicked + '').addClass('active');

        }
    });

    $('#alpha_list li').click(function() {
        var self = this;
        $('#alpha_list li').removeClass('active');
        $(self).addClass('active');
        $('.alphaResult').hide();
        $('#alpha_' + self.id.split('_')[1] + '').show();
    });

    $('#alphanav_all').click(function() {
        $('.alphaResult').show();
        $('.talentList').each(function() {
            if ($(this).find('tr:visible').length > 0) {
                $(this).parent().show();
            }
            else {
                $(this).parent().hide();
            }
        });
    });

    $('#advanced_search label').click(function(e) {
        var parentLi = $(this).parent('li');
        if (parentLi.hasClass('selected')) {
            parentLi.removeClass('selected');
            parentLi.find('.checkbox').removeAttr('checked');
        } else {
            parentLi.addClass('selected');
            parentLi.find('.checkbox').attr('checked', 'checked');
        };
    });

    $('.followLink').click(function() {
        var hrefVal = $(this).find('a').attr('href');
        if (hrefVal.indexOf('#') != -1) {
            $.scrollTo($(hrefVal), { duration: 500, offset: { top: -10} });
        } else {
            location.href = hrefVal;
        }
    });


//    if ($('.viewAll').length) {
//        $('.viewAll').mouseenter(function() {
//            viewSelf = $(this);
//            $(this).animate({ width: "78px" }, { queue: false, duration: 300 });
//            $(viewSelf).children('.viewAllTxt').delay(300).fadeIn(200);
//        });
//    };

//    if ($('.viewAll').length) {
//        $('.viewAll').mouseleave(function() {
//            viewSelf = $(this);
//            $(this).animate({ width: "23px" }, { queue: false, duration: 300 });
//            $(viewSelf).children('.viewAllTxt').fadeOut(0);
//        });
//    };

    if ($('a.scrollTo').length) {
        $('a.scrollTo').click(function(e) {
            e.preventDefault();
            var hrefVal = $(this).attr('href');
            $.scrollTo($(hrefVal), { duration: 500 });
        });
    }

    if ($('#enter_amount').length) {
        $('#enter_amount').click(function() {
            $('#donate_enter_amount').focus();
        });
    }

});

$(window).load(function() {
    if ($('.largeImgCentered p').length) {
        $('.largeImgCentered p').each(function() {
            var elHeight = $(this).height();
            $(this).css({
                position: 'absolute',
                top: '50%',
                marginTop: '-' + (elHeight / 2) + 'px'
            });
        })
    }
    Search();
});

function Search() {
    text = $('#filterInput').val();

    var containsName = true;
    var containsNameAll = false;
    var containsAdvanced = true;
    var containsFaculty = true;
    var containsLocation = true;
    if (text == '' || text == undefined || text == 'Search by Name' || text.length < 2) {
        containsNameAll = true;

        containsAdvancedCount = ($('.scrollableForm').children('ul').children('li:[class="selected"]').length);
        containsAdvancedActualCount = ($('.scrollableForm').children('ul').children('li').length);
        containsAdvancedAll = true;
        if (containsAdvancedCount != 0 && (containsAdvancedCount != containsAdvancedActualCount)) {
            containsAdvancedAll = false;
        }

        containsFacultyCount = ($('.faculty_filter').children('li:[class="selected"]').length);
        containsFacultyActualCount = ($('.faculty_filter').children('li').length);
        containsFacultyAll = true;
        if (containsFacultyCount != 0 && (containsFacultyCount != containsFacultyActualCount)) {
            containsFacultyAll = false;
        }

        containsLocationCount = ($('.location_filter').children('li:[class="selected"]').length);
        containsLocationActualCount = ($('.location_filter').children('li').length);
        containsLocationAll = true;
        if (containsLocationCount != 0 && (containsLocationCount != containsLocationActualCount)) {
            containsLocationAll = false;
        }
    }

    $('.talentList').each(function() {
       $(this).parent().show();
    });

    $('.talentList').find('tr').each(function() {
        $(this).show();
        if (!containsNameAll) {
            containsName = NameFilter($(this).children('td:first').children('a:first').children('div:first').children('div:first').children('h3:first').html(), text);
        }
        else {
            if (!containsAdvancedAll) {
                containsAdvanced = AdvancedFilter($(this).children('td:first').children('a:first').children('div:first').children('div:first').children('.keywords:first').val());
            }
            if (!containsFacultyAll) {
                containsFaculty = SearchTitleFilter($(this).children('td:first').children('a:first').children('div:first').children('div:first').children('.professorTitles:first').val(), '.faculty_filter');
            }
            if (!containsLocationAll) {
                containsLocation = SearchTitleFilter($(this).children('td:first').children('a:first').children('div:first').children('div:first').children('.locations:first').val(), '.location_filter');
            }
        }

        if (containsName && containsFaculty && containsLocation && containsAdvanced) {
            $(this).show();
        }
        else {
            $(this).hide();
        }
    });

    $('.talentList').each(function() {
        if ($(this).find('tr:visible').length > 0) {
            $(this).parent().show();
        }
        else {
            $(this).parent().hide();
        }
    });
}

function AdvancedFilter(keywords) {

    var contains = false;
    $('.scrollableForm').children('ul').children('li:[class="selected"]').children('label:first').each(function() {
        if (!contains) {
            var text = jQuery.trim($(this).text());
            if (keywords.indexOf(text) != -1) {
                contains = true;
            }
            else {
                contains = false;
            }
        }
    });
    return contains;
}

function SearchTitleFilter(title, ulName) {
    var contains = false;
    $(ulName).find('li:[class="selected"]').each(function() {
        if (!contains) {
            var labelValue = $(this).children('label:first').text();
            if (title == labelValue) {
                contains = true;
            }
            else {
                contains = false;
            }
        }
    });
    return contains;
}

function SearchCheckbox(checkbox) {
    //clearSearch(); - Uncomment if checkboxes should clear the search input
    Search();
}

function NameFilter(tr, text) {
    source = stripHTML(tr).toLowerCase();
    if (source.indexOf(text.toLowerCase()) != -1) {
        return true;
    }
    else {
        return false;
    }
}

function stripHTML(field) {
    return field.replace(/<([^>]+)>/g, '');
}

function clearSearch() {
    $('#filterInput').val('Search by Name');
    $('#filterInput').removeClass('hasValue');
}
