﻿$('document').ready(function(){
	//set display by page-type
    if(get_url_path() == '' || get_url_path() == 'home'){
        $('#bread_crumbs').css('display', 'none');
        $('#content').css({'padding-top':'114px'});//, 'height':'650px'
        $('#content div:first').removeClass('heading');
        //$('#content div h1:first').css('display', 'none'); //dont't display title on home page
        $('#left_nav_inner').addClass('home_page');
        $('#heading_image').css('display', 'none');
    }
    else if(is_landing_page()){
    	$('#bread_crumbs').css({top:'322px'}); 
        $('#content').css({'padding-top':'345px'});
        $('#heading_image').css({display:'block'});
        //$('#footer').css('bottom','0px');//helps IE6
    }
    else{
         $('#heading_image').css({display:'none'});
    }
    
    //check for font-size preference
    var font_size_preference = readCookie('font_size_preference');
    if(font_size_preference != null){
        $('body').css('font-size', font_size_preference);
    }
	   
    //style left nav
    $('#left_nav_list ul li:first').addClass('first');
    //$('#left_nav_list li:has(ul)').addClass('bullet_open'); done on the back end now
    $('#left_nav_list li a').addClass('nav');
    
    //set members section elements 
    if((get_url_path().substring(0,7)) == 'members'){
    	var iframe_src;
    	switch(queryString('member-type')){
			case 'member' :
				$('.nav_member').show();
				iframe_src = 'https://capweb.cap-mpt.com/MemberOnly/FrameJSP/main.jsp?member-type=Member';
				break;
			case 'group' :
				$('.nav_group').show();
				iframe_src = 'https://capweb.cap-mpt.com/MemberOnly/FrameJSP/main.jsp?member-type=Group';
				break;
			case 'hospital' :
				$('.nav_hospital').show();
				iframe_src = 'https://capweb.cap-mpt.com/MemberOnly/FrameJSP/main.jsp?member-type=HTP';
				break;
			case 'broker' :
				$('.nav_broker').show();
				iframe_src = 'https://capweb.cap-mpt.com/MemberOnly/FrameJSP/main.jsp?member-type=Broker';
				break;
			case 'PAC' :
				$('.nav_member').show();
				iframe_src = 'https://capweb.cap-mpt.com/MemberOnly/FrameJSP/public_affairs/pacs.jsp';
				break;
			case 'manager' :
				$('.nav_manager').show();
				iframe_src = 'https://capweb.cap-mpt.com/MemberOnly/FrameJSP/AdminLogin.jsp';
				break;
		}
		
		$('#principal_inner').height(1250);
		
    	$('#content').empty().append('<iframe id="members_iframe" height="1000" width="581" scrolling="no" frameborder="0" src="' + iframe_src + '"></iframe>')
        //var $bread_crumb_container = $('#bread_crumbs').empty().append('<span>Login</span>');
		$('#left_nav_list li:has(ul)').click(function(event){
              $('#left_nav_list li').removeClass('bullet_open').children('ul').slideUp().end().children('span').removeClass('active').attr({active:'false'}) ;
              var $this = $(this);
              if($this.children('ul').is(':hidden')) {
                $this
                  .addClass('bullet_open')
                  .children('ul').slideDown()
                  .end().children('span').addClass('active').attr({active:'true'})
              }
        })
            .children('ul').hide()
            .end()
            .children('span').css('cursor', 'pointer')
            .hover(function(){
                $(this).addClass('active');
            },
                function(){
                if($(this).attr('active') == 'false' || $(this).attr('active') == undefined){
                    $(this).removeClass('active');
                }
            }); 
			                     
        $('#left_nav_list li span[src]').click(function(){
        	//set all elements inactive
            $('#left_nav_list li span[src]').removeClass('active').attr({active:'false'});
            //set this element active and set source of iframe
			var $this = $(this);
            var src = $this.attr('src');
            $this.addClass('active').attr({active:'true'});
            $('#members_iframe')[0].src = src;
            return false;
        }).hover(function(){
                $(this).addClass('active');
            },
                function(){
                if($(this).attr('active') == 'false' || $(this).attr('active') == undefined){
                    $(this).removeClass('active');
                }
            })
            .css('cursor', 'pointer');       
    }
    
    //style bread crumb links
    $('#bread_crumbs a').addClass('nav');	

	/*Reset page-height to place footer at window bottom in the event our content is not taller than our window.*/
	set_height();
    window.onresize = function(){
        set_height();
    }
    
    /*adjust for difference in dispaly form OSX to Windows*/
    if(navigator.platform == "MacIntel"){
		$('#top_nav').css('top', '28px');
	}
    
    /*main navigation*/ 
	//rollovers
    $('#main_nav a img').each(function(){
    	var path = get_url_path();
        var $img = $(this);
        var $nav_a_tag = $img.parents('a');
        var href = $nav_a_tag.attr('href');
        var base_path = path.indexOf('/') == -1 ? path : path.substring(0, path.indexOf('/'));
        if(href.substring(1) == base_path){
        	swap_over($img);
			$nav_a_tag.replaceWith($img);
		}
 		else{
	        $nav_a_tag.hover(function(){
	            swap_over($img);
	        }, function(event){
	            swap_up($img);
	        });
        }
    });
   
    //preload
    $('#main_nav a img').each(function(){
        var rollSrc = $(this).attr('src');
        var rollOver = rollSrc.replace(/\./i, '_over.');
        $('<img>').attr('src', rollOver);
    });
    
    //font size control
    $('#change_size_plus').click(function(){
    	$('#principal_inner').css('height','auto');
		font_size(true);
		//set_height(); //needs more work
	});
	
	$('#change_size_minus').click(function(){
		font_size(false);
	});
    
    //search
    $('#search_input').focus(function(){
        $this = $(this);
        /*if(this.value == 'search'){
            this.value = '';
            $this.removeClass('placeholder').addClass('search_term');
        }*/
        $this.keypress(function(event){
            if(event.keyCode == 13){
                event.preventDefault();
                search(this.value);
            }
        });
		/*.blur(function(){
            if( ! this.value){
                this.value = 'search';
                $(this).removeClass('search_term').addClass('placeholder');
            }
        });*/
    });
    
    $('#search_button').click(function(){
        search($('#search_input').val());
    }).keypress(function(event){
        if(event.keyCode == 13){
            search($('#search_input').val());
        }
    });
    
    //set top navigation and footer navigation active state
    set_link_state($('#top_nav'));
    set_link_state($('#footer_nav'));
    
    //validate instant quote form 
    $('#quote_form').submit(function(){
    	var $this = $(this);
		if(validate_quote_form($('#txt_doctor_first_name', $this).val(), $('#txt_doctor_last_name', $this).val(), $('#txt_doctor_email', $this).val(), $('#txt_doctor_city', $this).val())){
			return true;
		}
		
		return false;
	});
	
	//order form 
	$('#RiskManagementServices-capform').submit(function(){	
		if( ! validate_order_form($('#edit-member-name').val(), $('#edit-membership-no').val())) return false;
		return true;	
	});
	
	//open files in a new window
	$('a[href*="sites/default/files"]', '#left_nav_list').attr('target', '_blank');
 
	//debug height info  
// $('<div></div>').append(
//        'Window Height: ' + $(window).height() 
//        + '<br />Container Height: ' + $('#container').outerHeight()
//        + '<br />Nav Container Height: ' + $('#left_nav_container').outerHeight()
//    ).appendTo($('body'));
    
        
});


function set_link_state($container){
	$container.children('a').each(function(){
		var $this = $(this);
		if(get_url_path() == ($this.attr('href').substring(1))){
			$this.replaceWith('<span class="active active_state">' + $this.text() + '</span>');
		}
	})
}

var original_principal_height = 0;
function set_height(){
	/* set left navigation bottom shadow*/
    var $left_nav_bottom = $('#left_nav_bottom');
    var left_nav_list_height = $('#left_nav_list').outerHeight();
    //console.log(left_nav_list_height);
    if(left_nav_list_height <= 500){
        $('#left_nav_inner').height(500);
        $left_nav_bottom.css({'height':'110px'}).addClass('nav_bottom_100');
    }else if (left_nav_list_height > 500 && left_nav_list_height < 580){  
        $('#left_nav_inner').height(550);
        $left_nav_bottom.css({'height':'60px'}).addClass('nav_bottom_50');
    }else{
        $left_nav_bottom.css({'height':'20px'}).addClass('nav_bottom');
    }

	/*set footer element position*/
    var $principal_inner = $('#principal_inner');
    var principal_height = $principal_inner.outerHeight();
    if(original_principal_height == 0){
        original_principal_height = principal_height;
    }
    var window_height = $(window).height();

    var left_nav_height = $('#left_nav_container').outerHeight();
    if(window_height > (left_nav_height + 92) && window_height != principal_height){
        if(original_principal_height < window_height){
            $principal_inner.height(window_height - 92);
        }
        else{
            $principal_inner.height(original_principal_height);
        }
    }
    else if(left_nav_height > (principal_height)){
        $principal_inner.height((left_nav_height < 650 ? 650 : left_nav_height));
    }
}

function isFF3(){
    return ($.browser.mozilla && /1\.9\.\d\.\d/.test($.browser.version));
}

function search(term){
    url = '/search/node/' + term;
    document.location.href = url;
}

function font_size(isIncrease){
    $body = $('body');
    current_size = $body.css('font-size');
    var num = parseFloat(current_size, 10);
    if(isIncrease && num < 14){
		++num;
	} 	
	else if(!isIncrease && num > 11){
		--num;
	}
    $body.css('font-size', num + 'px');
    createCookie('font_size_preference', num + 'px', 365);
}

function font_reset(){
    $('body').css('font-size', '11px');
    eraseCookie('font_size_preference');
}

function swap_over($img){
    var imgsrc = $img.attr('src');
    var imgsrcOver = imgsrc.replace(/\./i, '_over.');
    $img.attr('src', imgsrcOver);
}

function swap_up($img){
    if( ! $img.attr('landing')){//don't run on landing page naivigation
        var imgsrc = $img.attr('src');
        var imgsrcUp = imgsrc.replace(/_over/i, '');
        $img.attr('src', imgsrcUp);
    }
}

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);
}

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
} 

function queryString(param, url){
    if(arguments.length == 1){
        url = window.location.href;
    }
    var qs = url.substr((url.indexOf('?') + 1));
    qs = qs.split('#')[0];//account for named anchors
    var params = qs.split('&');
    for(var i = 0; i < params.length; i++){
        var pair = params[i].split('=');
        if(pair[0] == param){
            return pair[1];
        }
    }
    return '';
}

//open page content in new window for print
function printContent(){
    printWin = window.open('/print.html','mywin','left=20,top=20,width=700,height=700,toolbar=1,resizable=1,scrollbars=yes');
    printWin.focus();
    src_title = document.title;
    src_value = "<img src='/portals/0/skins/uhc/assets/images/logo.gif' alt='UHC logo'/>";
    src_value += $("div[id$='ContentPane']", '#dnn_ContentPane').html();
    counter = 10;
    waitfortarget();
}

function waitfortarget(){
        counter--;
        if ( ! printWin.document.getElementById('print_content')){
            if (counter > 0){
                timer=setTimeout("waitfortarget()", 1000);
            }
            else{
                alert('Unable to load print version. Please try again later.');
            }
        }
        else{
            donetarget();
        }
    }
    
function donetarget(){
    printWin.document.title = src_title;
    printWin.document.getElementById('print_content').innerHTML = src_value;
    printWin.print();
}

function switch_stylestyle(styleName){
    $('link[rel*=style][title]').each(function(i){
        this.disabled = true;
        if (this.getAttribute('title') == styleName) this.disabled = false;
    });
}

var current_path = 'x';
function get_url_path(){
	if(current_path == 'x'){
		var url = window.location.href;
		var fragment = url.substring(9);
		current_path = fragment.substring(fragment.indexOf('/') + 1);
		//console.log('run once');	
	}
	return current_path;
}

function is_landing_page(){
	var pattern = /^about_us$|^join_cap$|^products_and_services$|^risk_management$|^public_affairs$/;
	if(pattern.test(get_url_path())){
		return true;
	}
	return false;
}

 function validate_quote_form(first_name, last_name, emailAddress, city){
    var errorMessage = '';
    if( ! first_name) errorMessage += 'Please enter Physician\'s First Name\n';
    if( ! last_name) errorMessage += 'Please enter Physician\'s Last Name\n';
    if( ! emailAddress){
        errorMessage += 'Please enter E-mail Address\n';
    }
    else{
        if( ! emailAddress.match(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)){
           errorMessage += 'Please check formatting of E-mail Address\n';
        } 
    }
    if( ! city){
    	errorMessage += 'Please enter your city';
    }
    if(errorMessage) {
        alert(errorMessage);
        return false;
    }
    
    return true;
}

function validate_order_form(name, member_id){
	var errorMessage = '';
	if(!name) errorMessage += 'Please enter your name! \n';
	if(!member_id) errorMessage += 'Please enter your membership number! \n';
	if(errorMessage){
		alert(errorMessage);
		return false;
	}
	return true;	
}
