var page_select = "test";

var get_cookie_value = function(cookie_name) {
    var cookie_val = '';
    var start_index = document.cookie.indexOf(cookie_name+"=");
    
    if (start_index != -1) {    // if cookie has been set...
    
        start_index += cookie_name.length + 1;     // start index is now after the cookie name and = sign
        var end_index = document.cookie.indexOf(";", start_index);

        if (end_index == -1) {   // if cookie value is the last in the list, make end_index the end of the string
            end_index = document.cookie.length;
        }
        
        cookie_val = document.cookie.substring(start_index, end_index);
    
    } else {    // cookie has not been set
        cookie_val = null;
    }
    
    return cookie_val;
}

var get_page = function(cond,rel) {
        //alert("cond=" + cond + " rel=" + rel);
        var rel = $('#mainForm\\:it2').val();
        //alert("rel from it2=" + rel);
        if( rel == 'undefined')
        //alert("will set cookie to : " + cond);
        //--: there seems to be some timing issue here
        setExpiration(cond);
        setExpiration(cond);

        if( rel != "home") {
            var flash_dispatch_service_url =  SITEROOT + "/webservices/flashdispatchadapter" + "?rel=" + rel;
            try {
              window.location =   flash_dispatch_service_url;
            } catch(error){
                alert("error :"+error);
            }
        } else {
          window.location = SITEROOT + "/index.jspx";
        }
        //alert("flash_dispatch_service_url : " + flash_dispatch_service_url);
}

/*
var get_page_rb = function(cond) {
        var rel = $('#mainForm\\:it2').val();
        //alert("get_page_rb: cond=" + cond + " rel=" + rel);
        setExpiration(cond);
        var flash_dispatch_service_url =  SITEROOT + "/webservices/flashdispatchadapter" + "?rel=" + rel;
        try {
          window.location =   flash_dispatch_service_url;
        } catch(error){
            alert("error :"+error);
        }
}
*/

var show_rb = function(event) {
    //alert("show_rb");
    evokeModalDialog.setBgColor("#FFFFFF");
    evokeModalDialog.show('condition_select');
    page_select = $(this)[0].id;

    var component = $('#mainForm\\:it2');
    component.val(page_select); 

    //alert("id0: =" +  $(this)[0].id);
    if( page_select.indexOf(":") > 0 ){
        setCompVar(page_select.substring(5));
    } else {
        setCompVar(page_select);
    }
    event.preventDefault();
}


//var show_rb_global = function(cpage) {
var show_rb_global = function() {
    evokeModalDialog.setBgColor("#FFFFFF");
    evokeModalDialog.show('condition_select');
    var page_select = $('#mainForm\\:it2').val();
    //page_select = vcomp.val();
    //alert("page_select = " + page_select);
    setCompVar(page_select);
    //event.preventDefault();
}

var setCompVar = function(rel)   {
  try {
        var component = $('#mainForm\\:rbdest');
        component.val(rel); 
        //alert('component set to ' +  rel);
  } catch (err) {      
        alert('error : ' + err.message);
  }
}

var show_rb_flash = function(rel) {
    //alert("show_rb_flash rel: " + rel);

    var component = $('#mainForm\\:it2');
    component.val(rel); 

    evokeModalDialog.setBgColor("#FFFFFF");
    evokeModalDialog.show('condition_select');
    page_select = rel;
    setCompVar(rel);
}

var show_adv_story = function(group, type, subtype, rel) {
    //alert(group+', '+type+', '+subtype+', '+rel);
    homepageTrack(group, type, subtype, rel);
}

//var show_rb_flash_cond = function(rel) {
var show_rb_flash_cond = function(group, type, subtype, rel) {
    
    homepageTrack(group, type, subtype, rel);
    
    var cond = get_cookie_value('condition');
//    alert("document.cookie : " + document.cookie);
//    alert("show_rb_flash_cond : " + rel +  "cond cookie : " + cond);
        if( cond != null && cond != "undefined" && cond != "" && cond != "no")
        {
          //alert("will NOW invoke dispatch service");
            var flash_dispatch_service_url =  SITEROOT + "/webservices/flashdispatchadapter" + "?rel=" + rel;
            try {
              window.location =   flash_dispatch_service_url;
            } catch( error) {
                alert("error" + error);
            }
  
        } else {
                evokeModalDialog.setBgColor("#FFFFFF");
                evokeModalDialog.show('condition_select');
                page_select = rel;
                setCompVar(rel);
        }

}

//var browse_to_anchor = function(aname) {
var browse_to_anchor = function(advocate, type, subtype, aname) {
    homepageTrack(advocate, type, subtype, aname);
    window.location = "#"+aname;
}

var browse_to_global_page = function(group, type, subtype, rel) {
    //alert(rel);
    homepageTrack(group, type, subtype, rel);
    
    unbArray = new Array("what_is_enbrel","possible_side_effects","inject_enbrel","store_enbrel","enbrel_support","pay_for_enbrel", "co-pay_program");    

    unbstr = "unb:"
    for (i=0; i<unbArray.length; i++) {
        if (rel == unbArray[i]) {
            unbstr = "";
            break;
        }
    }
    
    var flash_dispatch_service_url =  SITEROOT + "/webservices/flashdispatchadapter" + "?rel=" + unbstr + rel;
    //alert(flash_dispatch_service_url);
    try {
        window.location =   flash_dispatch_service_url;
    } catch( error) {
        //alert("error" + error);
    }
}

var browse_to_pdf = function(group, type, subtype, rel) {
    //alert(rel);
    homepageTrack(group, type, subtype, rel);
    var fileName = '';
    
    if (rel == 'medication_guide') fileName = 'ENBREL-Medication-Guide.pdf';
    
    var filePath = SITEROOT + '/documents/' + fileName;

    try {
        window.open (filePath);
    } catch( error) {
        //alert("error" + error);
    }
}

//jQuery().ready(show_rb_flash_cond('your_symptoms'));

var condition_select = function(a,indy) {
	a.href = "/switch/" + page_select + "/" + indy;
}

var condi_rice = function()
{
	indy = 'no';
	maindiv = $('div#main');
	if (maindiv.hasClass('pso'))
	{
		indy = 'pso';
	}
	else if (maindiv.hasClass('psa'))
	{
		indy = 'psa';
	}
	else if (maindiv.hasClass('ra'))
	{
		indy = 'ra';
	}
	else if (maindiv.hasClass('as'))
	{
		indy = 'as';
	}
	else if (maindiv.hasClass('jia'))
	{
		indy = 'jia';
	}
	return indy;
}

var rb_init = function()
{
	//alert("hi there");
	jQuery(".no #main_menu li a.yes").click(show_rb);
	// check this because dante doesn't like it
	jQuery(".no #section_nav li a.yes").click(show_rb);
	jQuery(".no #prev_next_bar a.yes").click(show_rb);
	jQuery(".no #enbrel_advisor a.yes").click(show_rb);
	//jQuery("div#lang_select div.change_cond").click(show_rb);
}

/*
    $.ajax(
        {
            type: "POST",
            url: "WebService.asmx/Add",
            data: "{a:1,b:4}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
                alert(result.d);
            }
    }
    );
*/


var search_box_init = function()
{
        //alert('search_box_init');
	var init_value = 'Search ENBREL.com';
        //returns: {"results":[{"id":1,"name":"ENBREL Support"},{"id":2,"name":"Enbrel Co-Pay Card"},{"id":3,"name":"Enbrel"},{"id":6,"name":"How to use Enbrel"}]}
	//$('#search_box').flexbox('/services/search',
	$('#search_box').flexbox('phrases',
			{
				showArrow: false,
				width: 190,
				highlightMatchesRegExModifier:'gi',
				autoCompleteFirstMatch : false,
                                paging : false
			}
	);   

	$('#search_box_wide').flexbox('phrases',
                {
                    showArrow: false,
                    width: 390,
                    highlightMatchesRegExModifier:'gi',
                    autoCompleteFirstMatch : false,
                    paging : false
                }
	);   


	//$('#search_box').setValue(init_value);
	$('#search_box').click(function() {
        //alert('click');
        var term = $("input#search_box_input")[0].value;

        //$('#search_box_wide').setValue(term);
        //alert('input value:' + $("input#search_box_input")[0].value);
        $('#search_box').setValue(term);
        //--:$('#search_box_wide').setValue(term);
        //$("input#search_box_input")[0].value = term;
        //--: PAUSED until we can style flex: $('input#search_box_wide_input')[0].value = term;

          try {
          //alert("wills set to [ " + term + "]");
            var component = AdfPage.PAGE.findComponent("pt1:searchterm");
            component.setValue(term); 
          } catch(err) {
               alert('err=' + err);
          }
	});

}


var tab_init = function()
{
	$("ul.tab_list li").each( function()
	{	
		//alert (this.id);
		$(this).click(show_tab);
		if($(this).hasClass('active'))
		{	
			$(this).click();
		}
	});
}

var show_tab = function()
{
	//alert (this.id);
	$("ul.tab_list li").each( function()
	{	
		if($(this).hasClass('active'))
		{
			$(this).removeClass('active');
		}
	});
	$(this).addClass('active');
	
	
	$("div.tab_area").each( function()
	{	
		if($(this).hasClass('active'))
		{
			$(this).removeClass('active');
		}
	});
	$("div#" + this.id + "_area").addClass('active');
        validate_init();
}

var pic_frame_init = function()
{
	$("div.pic_pso_arm").append("<div class=\"bottom\"></div>");
	$("div.pic_as_joints").append("<div class=\"bottom\"></div>");
}

var print_init = function()
{
        $('ul#utility_nav li.print').click(function() {
            utilityTrack('print');
            window.print();
        });
}

// text size - BEGIN //

//variables
var textStatus = "small";

var textSizeArray = new Array(11,12,14,16);
var defaultSizeIndex = 1;
var containerDiv = "page_content";
//var currentSizeIndex = 1;
//document.cookie = "textSizeCookie=1; 0; path=/"
var text_size = function(direction) {
	if(direction == 'up')
	{

		set_text_size(currentSizeIndex + 1)

	}
	else if(direction == 'down')
	{

		set_text_size(currentSizeIndex-1)

	}
	match_heights();
}

var set_text_size = function( sizeIndex )
{
	if (sizeIndex > textSizeArray.length - 1)
	{
		sizeIndex = textSizeArray.length - 1;
	}
	else if (sizeIndex < 0)
	{
		sizeIndex = 0;
	}
	var text_container = false;
	if (document.getElementById(containerDiv) != null) {
	    text_container = document.getElementById(containerDiv);
        text_container.style.fontSize = textSizeArray[sizeIndex] + "px";
        currentSizeIndex = sizeIndex;
    	document.cookie = "textSizeCookie=" + sizeIndex + "; 0; path=/";
	}

}

var text_size_persist = function()
{
	$('ul#utility_nav li.size_icons img.up').click(function()
	{	
                utilityTrack('textIncrease');
                text_size("up");
	});
	$('ul#utility_nav li.size_icons img.down').click(function()
	{
                utilityTrack('textDecrease');
		text_size("down");
	});
	c_start = (document.cookie.indexOf("textSizeCookie=")) + 15;
	size = document.cookie.substring(c_start);
	if(isNaN(size))
	{
		currentSizeIndex = defaultSizeIndex;
	}
	else
	{
		size = parseInt(size);
		//alert (isNaN(0));
		if(isNaN(size))
		{
			currentSizeIndex = defaultSizeIndex;
		}
		else
		{
			currentSizeIndex = size;
		}
	}
	set_text_size(currentSizeIndex);

	
}


var contact_form_init = function()
{
	
}


// function to capture all styled form element clicks
var styleFormChecked = function(element) {
    //alert(element.id + "-" + element.checked + "-" + element.name);

    if (element.id.indexOf("cb_enbrel_treatment") > -1) toggleTreatmentDiv(element);
    if (element.id.indexOf("cb_enbrel_sup_treatment") > -1) toggleSupportTreatmentDiv(element);
    if (element.id.indexOf("sharps_taking_enbrel") > -1) toggleSharpsTaking(element);
    if (element.id.indexOf("sharps_enrolled_support") > -1) toggleSharpsEnrolled(element);
    if (element.id.indexOf('psa_doc') > -1) togglePSATreatment(element);
    //if (element.id.indexOf('escMilYes') > -1) alert("CJ");
}

var togglePSATreatment = function(el)
{
	toggle_psa_meds(el.value);
}

var toggleTreatmentDiv = function(el)
{
	var ind = $('input[name="frm_sel_indication"]').val();
        //var ind = document.forms['indication'].indication.value;
	var frm = 'div#dyn_' + ind + '_form';
	
	if (el.value == 'Y') 
	{
		$(frm + ' tr.enbrel_treatment_formdiv').show();
		req_form_status = "taking";
	} 
	else
	{
		$(frm + ' tr.enbrel_treatment_formdiv').hide();
		req_form_status = "nottaking";
	}
}

var toggleSupportTreatmentDiv = function(el)
{
	var ind = $('input[name="frm_sel_indication"]').val();
        //var ind = document.forms['indication'].indication.value;
	var frm = 'div#dyn_' + ind + '_form';

	if (el.value == 'Y') 
	{
		$(frm + ' tr.enbrel_treatment_treatstart').show();
		$(frm + ' tr.enbrel_treatment_nottaking').hide();
		sup_form_status = "taking";
	} 
	else
	{
		$(frm + ' tr.enbrel_treatment_treatstart').hide();
		$(frm + ' tr.enbrel_treatment_nottaking').show();
		sup_form_status = "nottaking";
	}	
}

var toggleSharpsTaking = function(el)
{	
	sharps_taking_status = (el.value == 'Y') ? "taking" : "nottaking";
}

var toggleSharpsEnrolled = function(el)
{	
	sharps_enrolled_status = (el.value == 'Y') ? "enrolled" : "notenrolled";
}

var preload_images = function()
{
	
    if (document.images)
    {
        preload_image_object = new Array();
        
        // set image url
        image_url = new Array();
        
        image_url[0] = SITEROOT + "/images/shell/bg_csmodal.png";
        image_url[1] = SITEROOT + "/images/shell/csmodal_ra.gif";
        image_url[2] = SITEROOT + "/images/shell/csmodal_pso.gif";
        image_url[3] = SITEROOT + "/images/shell/csmodal_psa.gif";
        image_url[4] = SITEROOT + "/images/shell/csmodal_as.gif";
        image_url[5] = SITEROOT + "/images/shell/csmodal_jia.gif";
        image_url[6] = SITEROOT + "/images/shell/nav/nav_understand-sel.gif";
        image_url[8] = SITEROOT + "/images/shell/nav/nav_learn-sel.gif";
        image_url[10] = SITEROOT + "/images/shell/nav/nav_support-sel.gif";
        image_url[12] = SITEROOT + "/images/shell/nav/nav_background.gif";
        image_url[13] = SITEROOT + "/images/shell/nav/nav_understand-over.gif";
        image_url[14] = SITEROOT + "/images/shell/nav/nav_learn-over.gif";
        image_url[15] = SITEROOT + "/images/shell/nav/nav_support-over.gif";
        
        for(i=0; i<image_url.length; i++) {
            preload_image_object[i] = new Image();
            preload_image_object[i].src = image_url[i];
        }
    }


}

var match_heights = function()
{
    mh = $('.masterHeight').height();
    $('.matchHeight').height(mh);
}

function track_init() {
    
    // PDF links
    $('a[href$=".pdf"]').click( function() {
        var el = $(this);
        pdfTrack(el);
    });
    
    // Enbrel Guide links
    $('#advisor_container div.advisor_link a').click( function() {
        var el = $(this);
        enbrelGuideTrack(el); 
    });
    
}

var main_init = function()
{
        //alert('inisde main_init');
        evokeModalDialog.eventLoad();
	print_init();
        text_size_persist();	
        pic_frame_init();
	//search_box_init();
	interstitial_init();
	email_page_init();
	share_page_init(); 
	glossary_init();
	rb_init();
	tab_init();
	accordion_init();
	video_init();
        schedulecall_init();
	slide_select_init();
        copay_form_init();
	wt_init();
        //validate_init();
        //results_init();
	rollover_init();
	track_init();
	preload_images();
	Custom.init();
        specialist_init();
        validate_init();
        match_heights();
        lightBoxInit();
        //alert(SITEROOT);
    }

function setExpiration(vcond)
{ 
    // alert("setExpiration vcond=" + vcond);
     var SECONDS_BIANNUAL = 60*60*24*(30*6); 
     var allcookies = document.cookie;
     var indx = allcookies.indexOf( "condition=" );
     var cond = vcond;
     var date = new Date();
     date.setTime(date.getTime()+(365*24*60*60*1000));
     var expiryDate = date.toGMTString();
     document.cookie = "condition=" + cond + ";" + " path=/; expires=" +  expiryDate;
}



var errors_on = false;

var toggleErrors= function()
{
	if (errors_on)
	{
		$('.error_container').removeClass('error_on');
		$('#right_rail_main .checkbox').each(function() {
			Custom.error(this.nextSibling);  // for search page callout
		});
		$('.finda_table .checkbox').each(function() {
			Custom.error(this.nextSibling);  // for find a derm/rheum T&C checkbox
		});
		
/*
		$('.checkbox').each(function() {
			Custom.error(this.nextSibling);
		});
		$('.radio').each(function() {
			Custom.error(this.nextSibling);
		});	
*/		errors_on = false;

	} else {
		$('.error_container').addClass('error_on');
		$('#right_rail_main .checkbox').each(function() {
			Custom.errorOff(this.nextSibling);  // for search page callout
		});
		$('.finda_table .checkbox').each(function() {
			Custom.errorOff(this.nextSibling);  // for find a derm/rheum T&C checkbox
		});
/*
		$('.checkbox').each(function() {
			Custom.errorOff(this.nextSibling);
		});
		$('.radio').each(function() {
			Custom.errorOff(this.nextSibling);
		});	
*/		errors_on = true;

	}	
}


var destroy_flash_element = function(flash_cont, flash_cont_parent) {
    swfobject.removeSWF(flash_cont);
    $('#'+flash_cont_parent).html('<div id="'+ flash_cont +'"></div>'); //recreates the flash holder DOM object that was destroyed by removeSWF
}


var lightBoxInit = function() {
    var pre_open = getQueryValue("pop");
    if(pre_open != "") {
        if(pre_open == "schedule_a_call") {
            try {
                c2cTrack('launch');       
                pop_schedulecall(null);
            }  catch(e) {
                //alert("error popping call scheduler");
            }
        }
    }
}

/* pass in name to get value */
var getQueryValue = function( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}


//alert('will call main_init');
jQuery().ready(main_init);
