/**
 * 
 * Loads all common scripts used on YBO
 * 
 * 
 */

var currentPage; // global location value

/**
 * Scrollpane initialization
 * 
 * @param none
 * @returns none
 */
var initScrollPane = function() {
	$('.pane').jScrollPane();
};


/**
 * Modal window initialization
 * 
 * @param none
 * @returns none
 */
var linkUrl;
var initModals = function() {
//this.modalElements = "<div class='share-modal' style='display:none'><div class='sm-wrap'></div></div>";
this.modalElements = "<div class='before-save-modal' style=''><div class='bs-wrap'></div></div>";
this.modalElements += "<div class='overlay' id='overlay'><div class='wrap'></div></div>";

$('body').append(this.modalElements);



this.loadModal = $('#overlay').overlay({
    oneInstance: false,
    api: true,
    onLoad: function() {
        var wrapper = this.getContent().find('div.wrap');
        
            wrapper.load(linkUrl);
    
    },
    expose: {
        color: '#a5a5a5',
        opacity: 0.7,
        closeSpeed: 1000
    }
});


	/**
	 * Initializes sharing options modal
	 * 
	 * @private
	 * @param none
	 * @returns none
	 

	this.shareModal = $('div.share-modal').overlay({
				oneInstance : false,
				api : true,
				onLoad : function() {
					var wrap = this.getContent().find('div.sm-wrap');
					if (wrap.is(':empty')) {
						wrap.load('../../share/default.aspx', null, function() {
									$('#shareForm').jFormm();
									focusClear();
								}); // this load the share form in page 7
					}
				},
				expose : {
					color : '#a5a5a5',
					opacity : 0.7,
					closeSpeed : 1000
				}
			});*/

	/**
	 * Initializes register before saving modal
	 * 
	 * @private
	 * @param none
	 * @returns none
	 */

	this.beforeSaveModal = $('div.before-save-modal').overlay({
				oneInstance : false,
				api : true,
				onLoad : function() {
					var wrap = this.getContent().find('div.bs-wrap');
					if (wrap.is(':empty')) {
						wrap.load('beforeSaveModal.html'); // this one loads the html for page 1
					}
				},
				expose : {
					color : '#a5a5a5',
					opacity : 0.7,
					closeSpeed : 1000
				}
			});
};



var closeFancyModal = function() {
$.fn.fancybox.close()
}


/**
 * Displays Modal window for "Add this" and recommend form
 * 
 * @public
 * @param none
 * @returns none
 */

var showShareModal = function() {
	//this.shareModal.load();
};

/**
 * Displays Modal window for Alert before saving
 * 
 * @public
 * @param none
 * @returns none
 * @type none
 */
var showBeforeSaveModal = function() {
	this.beforeSaveModal.load();
};


var showExtModal = function(url) {
    linkUrl = url;
    this.loadModal.load();
    return false;
};
/**
 * Set equal heights in all modules presented in home page
 * 
 * @public
 * @param none
 * @returns none
 */
var adjustHomeModules = function() {
	var moduleContainer = $('#modules');
	var modules = $('#modules > div.module');
	var moduleHeight = moduleContainer.height();

	$.each(modules, function() {
				$(this).height(300);
			});

};

/**
 * Clear input fields when user clicks on it
 * 
 * @public
 * @param none
 * @returns none
 */
/*var focusClear = function() {
	var defaultData = '';

	// clear input on focus
	$('input:text').focus(function() {
				defaultData = $(this).val();
				$(this).val('');
			});

	// if field is empty afterward, add text again
	$('input:text').blur(function() {
				if ($(this).val() === '') {
					$(this).val(defaultData);
				}
			});

};*/
$.fn.focusClear = function() {
    return this.focus(function() {
        if (this.value == this.defaultValue) {
            this.value = "";
        }
    }).blur(function() {
        if (!this.value.length) {
            this.value = this.defaultValue;
        }
    });
};


/**
 * Languages tooltip initialization
 * 
 * @public
 * @param none
 * @returns none
 */

var initLangTooltip = function() {
	var tooltip = $('#languageLink').qtip({
				// content: 'This is an active list element',
				content : {
					url : 'listOfLanguages.html' //declare html
				},
				show : 'mouseover',
				hide : 'unfocus',
				// hide: false,
				style : {
					// name: 'defaults', // Inherit from preset style
					tip : 'topMiddle',
					border : {
						radius : 5,
						color : '#f9f9f9'
					},
					padding : '5px 0px 7px 0px',
					width : {
						min : 120, // Defaults to 0, but in IE it doesn't show
									// nothing
						max : 120
					}
				},
				position : {
					corner : {
						target : 'bottomMiddle',
						tooltip : 'topMiddle'
					}
				},
				api : {
					onRender : function() {
						var qtip = $(this)[0].elements.tooltip;
						var qtipClose = qtip
								.append('<div class="close"></div>');
						$(qtipClose).bind('click', function(e) {
									$(qtip).qtip('hide'); // Hides the tooltip
								});
					}
				}

			});
	initQtipCloseEvents();
};

var initQtipCloseEvents = function() {
	// events to hide the tooltip when mouse leaves it
	$('.qtip').livequery(function() {
				// use the helper function hover to bind a mouseover and
				// mouseout event
				$(this).hover(function() {
						}, function() {
							$('.qtip').qtip('hide'); // Hides the tooltip
						});
			}, function() {
				// unbind the mouseover and mouseout events
				$(this).unbind('mouseover').unbind('mouseout');
			});

	// hide the tooltip when the user clicks some item
	$('.qtip a').livequery('click', function(e) {
				$('.qtip').qtip('hide'); // Hides the tooltip
			});
};

var initPhysicianTooltip = function(selectorId, content) {
    var tFavorites = $(selectorId).qtip({
        content: content,
        show: 'mouseover',
        hide: 'mouseout',
        // hide: false,
        style: {
            // name: 'defaults', // Inherit from preset style
            tip: 'bottomLeft',
            border: {
                radius: 2,
                color: '#da2a3e'
            },
            background: '#da2a3e',
            color: '#fff',
            padding: '0px 4px 0px 4px',
            textAlign: 'center',
            fontSize: '11px',
            fontWeight:'bold',
            width: {
                min: 100
                // Defaults to 0, but in IE it doesn't show nothing
                // ,max: 100
            },
            height:15
        },
        position: {
            corner: {
                target: 'topMiddle',
                tooltip: 'bottomLeft'
            }
        },
        api: {
            onRender: function() {
                var qtip = $(this)[0].elements.tooltip;
                qtip.addClass('qtip-physician');
            }
        }
    });
};

var goToPage = function(pageName) {
    window.location.href = pageName;

}
/*
 Individual Select decorator
*/

jQuery.fn.selectdecorator = function($options) {

    var defaults = {
        DIVClass: 'Select_Decorator_Holder',
        onChange: function() { }
    };

    $current = jQuery(this);
    $ID = $current.attr('id');
    jQuery.extend(defaults, $options);

    newSelect = '<div>';

    newSelect += '<select';
    newSelect += ' name="' + $current.attr('name');
    newSelect += '" id="' + $ID;
    newSelect += '" class="' + $current.attr('class');
    newSelect += '">';
    newSelect += $current.html();
    newSelect += '</select>';
    newSelect += '<span></span>';
    newSelect += '<ul class="selectDeco">';
    jQuery.each($current.find('option'), function() {
        newSelect += '<li val="' + jQuery(this).attr('value') + '">';
        newSelect += jQuery(this).html();
        newSelect += '</li>';
    });
    newSelect += '</ul>';
    newSelect += '</div>';

    $decorator = jQuery(newSelect);
    $decorator.addClass(defaults['DIVClass']);


    $current.parent().append($decorator);
    $current.remove();


    $decorator.find('ul').css('position', 'absolute');
    $decorator.find('ul').css('z-index', '99');
    $decorator.find('ul').hide();
    $decorator.find('span').css('display', 'block');

    $decorator.find('span').bind('click', function() {
        jQuery(this).parent().find('ul').slideDown('fast', function() {
            jQuery('body').bind('click', function() {
                jQuery(this).parent().find('ul.selectDeco').hide();
            });
        });
    }
	);

    $decorator.find('ul>li').bind('click', function() {
        jQuery(this).parent().parent().find('select').val(jQuery(this).attr('val'));
        jQuery(this).parent().parent().find('span').parent().unbind('click');
        jQuery(this).parent().hide();
        jQuery(this).parent().parent().find('span').html(jQuery(this).html());

        if (defaults['onChange'] != null) {
            defaults.onChange();
        }

    });

    $newSelect = jQuery('#' + $ID);

    $newSelect.attr('style', 'opacity:0;position:absolute;top:-3000px;');

    $setFlag = 0;
    $newSelect.find('option').each(
		function() {
		    if ($setFlag == 0) {
		        $newSelect.parent().find('span').html(jQuery(this).html());
		        $newSelect.val(jQuery(this).val());
		        $setFlag = 1;
		    }
		}
	);
}



var selectedLanguage;
jQuery.fn.selectdecoratorForLanguageDD = function($options) {


    var defaults = {
        DIVClass: 'Select_Decorator_Holder',
        onChange: function() { __doPostBack('ddlVariation', ''); }
    };

    $current = jQuery(this);
    $ID = $current.attr('id');
    jQuery.extend(defaults, $options);

    newSelect = '<div>';

    newSelect += '<select';
    newSelect += ' name="' + $current.attr('name');
    newSelect += '" id="' + $ID;
    newSelect += '" class="' + $current.attr('class');
    newSelect += '">';
    newSelect += $current.html();
    newSelect += '</select>';
    newSelect += '<span id="span_dd"></span>';
    newSelect += '<ul class="selectDeco">';
    jQuery.each($current.find('option'), function() {

        if (jQuery(this).attr('selected')) {
            selectedLanguage = jQuery(this).attr('text');
        }
        newSelect += '<li val="' + jQuery(this).attr('value') + '">';
        newSelect += jQuery(this).html();
        newSelect += '</li>';
    });
    newSelect += '</ul>';
    newSelect += '</div>';

    $decorator = jQuery(newSelect);
    $decorator.addClass(defaults['DIVClass']);


    $current.parent().append($decorator);
    $current.remove();


    $decorator.find('ul').css('position', 'absolute');
    $decorator.find('ul').css('z-index', '99');
    $decorator.find('ul').hide();
    $decorator.find('span').css('display', 'block');

    $decorator.find('span').bind('click', function() {
        jQuery(this).parent().find('ul').slideDown('fast', function() {
            jQuery('body').bind('click', function() {
                jQuery(this).parent().find('ul.selectDeco').hide();
            });
        });
    }
	);

    $decorator.find('ul>li').bind('click', function() {
        jQuery(this).parent().parent().find('select').val(jQuery(this).attr('val'));
        jQuery(this).parent().parent().find('span').parent().unbind('click');
        jQuery(this).parent().hide();
        jQuery(this).parent().parent().find('span').html(jQuery(this).html());

        if (defaults['onChange'] != null) {
            defaults.onChange();
        }

    });

    $newSelect = jQuery('#' + $ID);

    $newSelect.attr('style', 'opacity:0;position:absolute;top:-3000px;');

    if (selectedLanguage != null) {
        document.getElementById("span_dd").innerHTML = selectedLanguage;
    }
}


/*
* Inits the left navigation menu behavior and styling
* 
* @public
* @param none
* @returns none 
**/


var initSideNav = function() {
    $("#sideNav dd ul li a.current").parent().addClass("current");
};

/*
 * 
 * Global on Dom ready initializations
 * 
 */
$(window).load(function() {
    /* Detect IE and set class for body */
    var isIE = $.browser.msie;
    if (isIE) {
        $('body').addClass('isIE');
    }

    /* navigation behavior */
    $('#globalNav > .items').superfish().find('ul').bgIframe({ opacity: false });

    /* Initialize Modal */
    initModals();

    //focusClear();

    $("div.search input:text, #finder input:text").focusClear();

    /* Initialize Tooltip that shows the languages list */
    initLangTooltip();

    /* Binds Modal to "Share" link */

    $("#shareLink, .contentBox").fancybox({
        'frameHeight': 500,
        'frameWidth': 600,
        'hideOnContentClick': false
    });
    $("a.profileEmail").fancybox({
        'frameHeight': 450,
        'frameWidth': 750,
        'hideOnContentClick': false
    });


    /*
    * Global initialization of section specific functionalities
    * Uncomment if config.js is not being used.
    */


    adjustHomeModules();
    initSideNav();
    initScrollPane();


    $("#tabs ul").tabs("#pages > div", { history: true });
    initTooltip();
    $('textarea#expandingText').autoResize({ onResize: function() {
        initScrollPane();
    }
    });


    $("a.maps").fancybox({
        'frameWidth': 800,
        'frameHeight': 550
    });

    $("a.iframe").fancybox();

    $("a.ajax").fancybox();

    $("a.iframe2").fancybox({
        'frameWidth': 560,
        'frameHeight': 340
    });
    
    $("div.search select").selectdecorator(
		         {
		             DIVClass: "searchSelect"
		         }
		      );

    // Added for language dropdown
    $("div.variation select").selectdecoratorForLanguageDD(
	            {
	                DIVClass: "languageSelect"
	            }
		      );


    // contact us dropdown
    $(".contact-us-l select").selectdecorator(
	            {
	                DIVClass: "languageSelect"
	            }
		      );

    // result page dropdown
    $("#result_main select").selectdecorator(
	            {
	                DIVClass: "languageSelect"
	            }
		      );
    $(".notesArea select").selectdecorator(
	            {
	                DIVClass: "languageSelect"
	            }
		      );


    $("h1").css({ 'color': '#a4b40f', 'font-family': 'Times New Roman', 'font-size': '65px', 'font-style': 'italic', 'font-weight': 'normal'})
    setTextTransform();
    $("h2").css({ 'color': '#DE265A', 'font-size': '19px', 'font-weight': 'normal' });
    $("#modules .module h2").css({ 'color': '#515151', 'font-size': '20px', 'font-weight': 'normal' });
    $('#subHeader h1').css({ 'color': '#a4b40f', 'text-transform': 'lowercase', 'font-size': '44px' });
    $('#headerSmall h1').css({ 'font-size': '48px' });
    $('.avenir-book-h3 h3').css({ 'color': '#7b7b7b' });

    // No results found msg on results.aspx
    $('#CSR_NO_RESULTS').css({ 'color': '#dd2559', 'font-size': '18px' });
    $('#CSR_NO_RESULTS ol').css('list-style-type', 'disc');

    $('.avenir-book-h2 h2').css({ 'margin-bottom': '-5px', 'font-size': '21px' });
    $('#center h4 font').css({ 'color': '#a4bf0f', 'font-family': 'sans-serif', 'font-size': '20px', 'font-weight': 'normal' });
    $('#center h4').css({ 'color': '#a4bf0f', 'font-family': 'sans-serif', 'font-size': '20px', 'font-weight': 'normal' });

    // bypassing the style on physician profile page
    $('#center #resume h4').css({ 'color': '#3C3C3C', 'font-size': '12px' });
    $('#headline, #center h3').css({ 'color': '#3c3c3c', 'font-weight': 'normal' });

    // on physician profile page
    $('#center #info h1').css({ 'font-size': '42px', 'text-transform': 'none' });

    $('h6').css({ 'color': '#dd2559', 'font-weight': 'normal' });

    // physicianfinderresult page's h1,h2 need overriding
    $('.SuggestionCell h1').css({ 'font-size': '48px' });
    $('.SuggestionCell h2').css({ 'margin-bottom': '0px' });

});   // ends global init

