/*
*
* ACOG JS Utilities
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Global Variables */


/* End Global Variables*/

var iframeHeight;
var detectIframe = false;

function ValidateEmailRegex(email) {
    var reg = new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
    return reg.test(email);
}

function time() {
    if (iframeHeight == null && detectIframe) {
        iframeHeight = $("iframe").contents().find("body").height() + 30;
        $("iframe").css("height", iframeHeight + "px");
    }
}

$(document).ready(function() {
    if ($("iframe").css("height") == "150px") { detectIframe = true; }
    $("iframe").load(function() {
        if (detectIframe) {
            iframeHeight = $("iframe").contents().find("body").height() + 30;
            $("iframe").css("height", iframeHeight + "px");
        }
    });

    $('.custom-dd').customDD();
    $('.right_rail .buyers_guide input.text').inputFocus('Search...');
    $('.right_rail .obgyn_locator input.text').inputFocus('Search...');
    //$('.search_box input:text').inputFocus('Search ACOG');
    //search by keyword
    $('.search_box #sbkInput').click(function() {
    var value = $('.search_box #sbkInput').attr("value").trim();
        if (value == "Search By Keyword" || value == "Search ACOG" || value == "Enter Search Keyword" || value == "Search Keyword")
            $('.search_box #sbkInput').attr("value", "");
    });

    $('.search_box #sbkInput').blur(function() {
        var value = $('.search_box #sbkInput').attr("value").trim();
        if (value == "")
            $('.search_box #sbkInput').attr("value", "Search By Keyword");
    });
    //search by keyword button
    $('.search_box .search_btn').click(function() {
        var value = $('.search_box #sbkInput').attr("value").trim();
        if (value == "" || value == "Search By Keyword" || value == "Search ACOG" || value == "Enter Search Keyword" || value == "Search Keyword") {
            var url = $('#sbKeyword').attr("href");
            url = url.replace("?Keyword=", "");
            window.location = url;
        }
        else
            window.location = $('#sbKeyword').attr("href") + $('.search_box #sbkInput').attr("value");

    });

    //home page patient topics
    $('.wrap input').click(function() {
        var FAQSearch = $(this).siblings('a').attr('href');
        window.location = FAQSearch + '?Topics=' + $('.custom-dd h3 a').attr("id");
    });

    //buyers_guide
    $('.buyers_guide .submit').click(function() {
        if ($(this).siblings('.text').val() != null && $(this).siblings('.text').val() != "") {
            var url = $(this).attr('rel') + "?";
            $(this).siblings('input').each(function() {
                url += $(this).attr('name') + "=" + $(this).val() + "&";
            });
            window.open(url);
        }
    });

    //media archive right rail module
    $('.media_archive_dd').bind('change', function(ev) { window.location = $(this).val(); });


    $('.todays_headline input:text').inputFocus('Email Address');
    $('#search_resources input:text').inputFocus('Enter Search Keyword');
    $('.header .search_box input:text').inputFocus('Enter Search Keyword');

    $("#home_accordion").accordion();
    $("#home_accordion").accordion("option", "icons", false);

    if (homeCarouselAutoStart == false) {
        $('#top_carousel').jcarousel({
            //auto:scroll_time,
            wrap: 'both',
            scroll: homeCarouselScrollItems,
            initCallback: home_carousel_initCallback,
            itemVisibleInCallback: home_carousel_itemVisibleInCallback,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            visible: 1
        });
    }
    else {
        $('#top_carousel').jcarousel({
            auto: homeCarouselScrollTime,
            wrap: 'both',
            scroll: homeCarouselScrollItems,
            initCallback: home_carousel_initCallback,
            itemVisibleInCallback: home_carousel_itemVisibleInCallback,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            visible: 1
        });
    }

    if (exploreAcogAutoStart == false) {
        $('#explore_carousel').jcarousel({
            wrap: 'both',
            scroll: exploreAcogScrollItems,
            initCallback: explore_carousel_initCallback,
            itemVisibleInCallback: explore_carousel_itemVisibleInCallback,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            visible: 5
            //size:15 - value is set on page render since the page number of items could vary
        });
    }
    else {
        $('#explore_carousel').jcarousel({
            auto: exploreAcogScrollTime,
            wrap: 'both',
            scroll: exploreAcogScrollItems,
            initCallback: explore_carousel_initCallback,
            itemVisibleInCallback: explore_carousel_itemVisibleInCallback,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            visible: 5
            //size:15 - value is set on page render since the page number of items could vary
        });
    }

    if (acogSpotlightAutoStart == false) {
        $('#bottom_carousel').jcarousel({
            wrap: 'both',
            scroll: acogSpotlightScrollItems,
            initCallback: bottom_carousel_initCallback,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            visible: 1
        });
    }
    else {
        $('#bottom_carousel').jcarousel({
            auto: acogSpotlightScrollTime,
            wrap: 'both',
            scroll: acogSpotlightScrollItems,
            initCallback: bottom_carousel_initCallback,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            visible: 1
        });
    }

    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tablist li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tablist li").click(function() {

        $("ul.tablist li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content

        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });

    //configure modal dialog boxes    
    $(".modal_dialog").dialog({
        autoOpen: false,
        resizable: false,
        modal: false,
        draggable: false,
        buttons: {
            "Close": function() { $(this).dialog("close"); }
        },
        open: function(event, ui) {
            $(this).children(':submit:first').focus();
        }
    });
    $("form:first").append($('.ui-dialog.ui-widget')); //place dialog inside of page-wide form
    $(".modal_dialog :submit").button();
    //open email dialog onClick
    $(".widget_box li.email_link a").click(function() {

        var pos = $(this).position();
        var width = $("#mail_friend").dialog("option", "width");

        $("#mail_friend").dialog("option", "title", "Email a Friend");
        $("#mail_friend").dialog("option", "position", [pos.left - width, pos.top + 20]);
        $("#mail_friend").dialog("open");
        //make submit button part of the button pane if not already        
        if (!$(".ui-dialog :submit:first").parent().hasClass('ui-dialog-buttonset')) {
            var btnSet = document.createElement("div");
            $(btnSet).addClass("ui-dialog-buttonset");
            $(btnSet).append($(".modal_dialog :submit"));
            $(".ui-dialog-buttonpane:first").append(btnSet);
        }

    });

    setTimeout("time()", 100);
});

var home_carousel_counter = 0;
//var times_to_scroll = 2;
var scroll_time = 5;

function bottom_carousel_initCallback(carousel, li, index) {
    carousel.clip.hover(
	function() {
	    carousel.stopAuto();
	}, function() {
	    if (carousel.options.auto != 0) carousel.startAuto();
	});

    $('.btm_carousel_wrap .controls .next').click(function() {
        carousel.startAuto(0);
        carousel.next();
        $('.btm_carousel_wrap .controls .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_block_icon.gif")');
        return false;
    });

    $('.btm_carousel_wrap .controls .prev').click(function() {
        carousel.startAuto(0);
        carousel.prev();
        $('.btm_carousel_wrap .controls .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_block_icon.gif")');
        return false;
    });

    $('.btm_carousel_wrap .controls .pause').click(function() {
        if (carousel.options.auto == 0) {
            carousel.startAuto(acogSpotlightScrollTime);
            $('.btm_carousel_wrap .controls .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/pause_block_icon.gif")');
        }
        else {
            carousel.startAuto(0);
            $('.btm_carousel_wrap .controls .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_block_icon.gif")');
        }
        return false;
    });
}

function explore_carousel_initCallback(carousel, li, index) {
    carousel.clip.hover(
	function() {
	    carousel.stopAuto();
	}, function() {
	    if (carousel.options.auto != 0) carousel.startAuto();
	});

    $('#explore_controls .left a').click(function() {
        carousel.startAuto(0);
        carousel.scroll($.jcarousel.intval($(this).text()) - 4);
        $('#explore_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_block_icon.gif")');
        return false;
    });

    $('#explore_controls .right .next').click(function() {
        carousel.startAuto(0);
        carousel.next();
        $('#explore_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_block_icon.gif")');
        return false;
    });

    $('#explore_controls .right .prev').click(function() {
        carousel.startAuto(0);
        carousel.prev();
        $('#explore_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_block_icon.gif")');
        return false;
    });

    $('#explore_controls .right .pause').click(function() {
        if (carousel.options.auto == 0) {
            carousel.startAuto(exploreAcogScrollTime);
            $('#explore_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/pause_block_icon.gif")');
        }
        else {
            carousel.startAuto(0);
            $('#explore_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_block_icon.gif")');
        }
        return false;
    });
}

function explore_carousel_itemVisibleInCallback(carousel, li, index) {
    $('#explore_controls > ul.left > li').removeClass("active");
    $('#explore_controls > ul.left > li').eq(Math.floor((index - 1) / 5)).addClass("active");
}

function home_carousel_initCallback(carousel, li, index) {
    /* Pause autoscrolling if the user moves with the cursor over the clip. */
    carousel.clip.hover(
	function() {
	    carousel.stopAuto();
	}, function() {
	    if (carousel.options.auto != 0) carousel.startAuto();
	});

    $('#carousel_controls .left a').click(function() {
        carousel.startAuto(0);
        carousel.scroll($.jcarousel.intval($(this).text()));
        $('#carousel_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_ico.gif")');
        return false;
    });

    $('#carousel_controls .right .next').click(function() {
        carousel.startAuto(0);
        carousel.next();
        $('#carousel_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_ico.gif")');
        return false;
    });

    $('#carousel_controls .right .prev').click(function() {
        carousel.startAuto(0);
        carousel.prev();
        $('#carousel_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_ico.gif")');
        return false;
    });

    $('#carousel_controls .right .pause').click(function() {
        if (carousel.options.auto == 0) {
            carousel.startAuto(homeCarouselScrollTime);
            $('#carousel_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/pause_ico.gif")');
        }
        else {
            carousel.startAuto(0);
            $('#carousel_controls .right .pause a').css('background-image', 'url("/ACOGProject/ACOG/frontend/images/play_ico.gif")');
        }
        return false;
    });
}

/* Home Carousel Slide Callback Function */
function home_carousel_itemVisibleInCallback(carousel, li, index) {
    $('#carousel_controls .left li').addClass(function() {
        $(this).removeClass('active');
        if ($(this).text() == index) return 'active';
    });
}

/*
*   Custom print function that prepares page with correct CSS before sending to print dialog
*/
function acogPrint() {
    if (window.print) {
        //TODO: implement switching stylesheets to print version/redirect to print page
        window.print();
    } else {
        return false;
    }
}

/*
*   Clears the default text of text boxes onFocus and returns it onBlur
*   Requires default text to be stored in title attribute of the element
*/
function toggleWatermark(elem) {
    if (elem.nodeName.toLowerCase() == "input" && $(elem).attr("type").toLowerCase() == "text") {
        if ($(elem).val() == $(elem).attr("title")) {
            $(elem).removeClass('default_text');
            $(elem).val('');
        } else if ($(elem).val() == '') {
            $(elem).addClass('default_text');
            $(elem).val($(elem).attr("title"));
        }
    } else {
        return false;
    }
}

/*!
* Custom Focus/Blur Function
*
* Pass in defalut text.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$.fn.inputFocus =

	function(str) {
	    $(this).focus(function() {
	        if ($(this).val() == str) $(this).val("");
	    });
	    $(this).blur(function() {
	        if ($.trim($(this).val()) == "") $(this).val(str);
	    });
	}

/*!
* Custom Drop Down Select box: Creates a custom styled dropdown box that will still function in forms
*
* All that is required is a normal select element.  This function hides the select dropdown and creates
* an unordered list (UL) of options.  Events are attached to the new UL so any change the user makes
* to the UL will be reflected in the hidden dropdown. This way forms will still handle the dropdown.  
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$.fn.customDD =

	function() {
	    if ($(this).length > 0) {
	        $(this).each(function() {

	            var parent = $(this);
	            var select = parent.find("select");
	            var title = $("<h3><a href='javascript:void(0)'></a></h3>");
	            var li = $("<li></li>");
	            var a = $("<a></a>");
	            var opt = null;
	            var custom_ul = $("<ul></ul>");

	            title.find("a").text(select.find(":selected").text());
	            parent.append(title);

	            // Create UL from select dropdown
	            select.children().each(function() {

	                opt = $(this);
	                a.attr({ "name": opt.text(), "href": "javascript:void(0)", "id": opt.val() }).html(opt.html());
	                if (a.attr("id") != "") { a.addClass("selectable"); }
	                custom_ul.append(li.append(a));

	                // Reset 
	                a = $("<a></a>");
	                li = $("<li></li>");
	            });

	            custom_ul.insertAfter(parent.find("h3"));
	            custom_ul = parent.find("ul")


	            // Attach event to drop down button
	            title.click(function() {
	                var act_ul = $(this).next("ul");
	                act_ul.parents(".custom-dd").toggleClass("active");
	                act_ul.slideToggle("fast");


	                return false;
	            });

	            // Set hidden dropdown and dropdown title
	            custom_ul.find("li a").click(function() {
	                var clicked = $(this);

	                // Find the correspoding option in the hidden select and set to selected
	                // Change the title text to the clicked elements
	                select.find("option[value=" + clicked.attr("name") + "]").attr("selected", "true");
	                title.find("a").text(clicked.text());
	                title.find("a").attr("id", clicked.attr("id"));
	                if (clicked.hasClass("selectable") && !title.find("a").hasClass("selectable")) { title.find("a").addClass("selectable"); }
	                else if (!clicked.hasClass("selectable") && title.find("a").hasClass("selectable")) { title.find("a").removeClass("selectable"); }
	                custom_ul.slideUp();
	                custom_ul.parents(".custom-dd").removeClass("active");
	                return false;

	            });
	        });
	    }
	}
