/**
 * @author m1010949
 */

//-------------------------------------------------------------------------------------------
// GLOBAL VAR USED TO DETERMINE WHETHER FLASH VIGNETTES HAS BEEN LOADED
// THIS VALUE IS TOGGLED BY A CALLBACK FROM vignettes.swf to swfVignetteCallback()
//------------------------------------------------------------------------------------------
if (typeof (console) === 'undefined' || console == null) {
    var console = { log: function () { } };
}
var isVignetteLoaded = false;
var redirect_fn = function (href) { location.href = href; };

$(document).ready(function () {

    if (scripts_isIE6) {
        $(window).load(function () {
            $(document).pngFix();
        });
    }

    //-------------------------------------------------------------------------------------------
    // SETUP WEBSITE DROP-DOWN
    //------------------------------------------------------------------------------------------ 
    $('a.dd').click(function () {
        if ($('#nav').css("height") != "38px") {
            ddMenuClose();
        } else {
            $('#nav').animate({
                height: "80px"
            }, 500);
            $('#moreSites').css("visibility", "visible").animate({
                opacity: 1.0
            }, 500);
        }
    });


    $('.overlabel').focus(function () {
        $this = $(this);
        if ($this.attr("title") == $this.val()) {
            $this.val("")
        }
    });

    $('.overlabel').blur(function () {
        $this = $(this);
        if ($this.val() == "")
            $this.val($this.attr("title"))
    });

    $('.overlabel').click(function () { //ie6 fix
        $this = $(this);
        if ($this.val() == "Enter Your Zip Code")
            $this.val('')
    });
    $('#drLocZip, #drLocZip_1').keypress(function (event) {
        if (event.keyCode == '13') {
            window.location.href = "/doctor-locator/index.shtml?val=" + $(this).val();
        }
    });


    if (swfobject.hasFlashPlayerVersion("8.0.0")) {
        $('#callout_tvspot_html').hide();
        $('#callout_tvspot_swf').show();
    }
    $(".tv-spot-overlay").click(function () {
        openDivCenter("tv-ads-overlay", "closeBtnLink");
        soundOff();
        var vars = {}
        var params = {
            scale: "noScale",
            salign: "",
            menu: "false",
            allowFullScreen: "true",
            scale: "showall",
            wmode: "transparent"
        };
        var attributes = {
            id: "swfTVSpot",
            name: "swfTVSpot"
        };
        swfobject.embedSWF("/swf/cibaplayer.swf", "flashcontent", "848", "430", "8.0.0", "/swf/expressInstall.swf", vars, params, attributes);
        //playVideo is available in flash via externalInterface
        //pauseVideo is available in flash via externalInterface
    });

	$(".AOAND").click(function () {
        openDivCenter("tv-ads-overlay", "closeBtnLink");
        soundOff();
        var vars = {}
        var params = {
            scale: "noScale",
            salign: "",
            menu: "false",
            allowFullScreen: "true",
            scale: "showall",
            wmode: "transparent"
        };
        var attributes = {
            id: "swfTVSpot",
            name: "swfTVSpot"
        };
        swfobject.embedSWF("/swf/aonda/cibaplayer.swf", "flashcontent", "848", "430", "8.0.0", "/swf/expressInstall.swf", vars, params, attributes);
        //playVideo is available in flash via externalInterface
        //pauseVideo is available in flash via externalInterface
    });
	
	$(".AOA").click(function () {
        openDivCenter("tv-ads-overlay", "closeBtnLink");
        soundOff();
        var vars = {}
        var params = {
            scale: "noScale",
            salign: "",
            menu: "false",
            allowFullScreen: "true",
            scale: "showall",
            wmode: "transparent"
        };
        var attributes = {
            id: "swfTVSpot",
            name: "swfTVSpot"
        };
        swfobject.embedSWF("/swf/aqua/cibaplayer.swf", "flashcontent", "848", "430", "8.0.0", "/swf/expressInstall.swf", vars, params, attributes);
        //playVideo is available in flash via externalInterface
        //pauseVideo is available in flash via externalInterface
    });
	


    $("#stf").click(function () {
        $('#frndPopup_frame').attr('src', "/share-with-friends/share-with-friend-iframe.shtml")
        openDivCenter("stfBlock", "closeBtn1");
        return false;
    });


    $(".selLang").click(function () {
        if (scripts_isIE6) {
            // ie6 has problem with position relative superscripted characters bleeding thru, similiar to 
            // when a select input box bleeds thru. 
            var disp = $("#cntryDD").css("display");
            if (disp == "block") {
                // hide superscripted characters in promo below
                $("#featureContentInfoTopPromo > sup").css("visibility", "visible");
            } else {
                // show superscripted characters in promo below
                $("#featureContentInfoTopPromo > sup").css("visibility", "hidden");
            }
        }
        $("#cntryDD").slideToggle('medium');
    });


    /* START EVENT TRACKING */



    //track external links, any link with rel="external" will be tracked
    $('[rel="external"]').click(function () {
        var pageName = ga_getExternalLinkName($(this).attr("href"));
        ga_trackPage(pageName);
        return true;
    });

    $('input.lifeStyleEle').click(function () {
        if ($(this).is(':checked')) {
            var elstr = $(this).attr("id")
            var elstr2 = elstr.replace(/lse_/, "");
            var elid = parseInt(elstr2);
            if (elid <= 30)
                ga_trackEvent("AO_Website_Homepage_Interaction", "Video_Lifestyle_Statements", lifeStyleElementsGA[elid - 1]);
            else if (elid >= 31 && elid <= 33)
                ga_trackEvent("AO_Website_NewToContacts", "NewToContacts_CL_Benefits", lifeStyleElementsGA[elid - 1]);
            else if (elid >= 34)
                ga_trackEvent("AO_Website_NewToContacts", "NewToContacts_Issues_Eyeglasses", lifeStyleElementsGA[elid - 1]);
        }
    });

    /*************************************************************
    * Generic click event to fire google analytic report 
    * works on metadata and json(defined in airoptix-ga-matrix.js)
    ************************************************************/
    $('._gaData').click(function () {
        var $this = $(this);
        var data = $this.metadata(); /*
		console.group('Google Matrix');
		console.log( 'Category: ' + gaMatrix.category[data.C] )
		console.log( 'Action: ' + gaMatrix.action[data.A] )
		console.log( 'Label: ' + gaMatrix.label[data.L] )
		console.groupEnd();
		return false; */
        if ($this.is(":radio") || $this.is(":checkbox")) {
            if ($this.is(':checked')) {
                ga_trackEvent(gaMatrix.category[data.C], gaMatrix.action[data.A], gaMatrix.label[data.L]);
            }
        } else {
            ga_trackEvent(gaMatrix.category[data.C], gaMatrix.action[data.A], gaMatrix.label[data.L]);
        }
    });

    $('._gaPage').click(function () {
        var data = $(this).metadata();
        ga_trackEvent(data.A);
    });

    $('[gadata]').click(function (evt) {
        evt.preventDefault();
        var data = eval($(this).attr('gadata'));
        ga_trackEvent(data[0], data[1], data[2]);
        setTimeout('redirect_fn("' + $(this).attr('href') + '")', 350);
    }
    );

    /* END EVENT TRACKING */

});


//get flash object for callback reference
function thisMovie(movieName) {
   var isIE = navigator.appName.indexOf("Microsoft") != -1;
   return (isIE) ? window[movieName] : document[movieName];
}

function swfVignetteCallback()
{
   // callback function from vignettes.swf
   // so we can easily determine if vignettes exists in our document.
   isVignetteLoaded = true;
}

function testForVignetteFlash()
{
   //alert("isVignetteLoaded: "+isVignetteLoaded);
   if(isVignetteLoaded) return true
   else return false;
}

function soundOn()
{
	if (testForVignetteFlash() ) {
	   //alert("calling sound on");
	   thisMovie("swfVignettes").uproar();
	}
}

function soundOff()
{
	if (testForVignetteFlash()) {
	   //alert("calling sound off");
	   thisMovie("swfVignettes").silence();
	}
}

	
//function gives the parameter value from the query string, takes query string and parameter name as parameters
function getParameterValue1(parameterName){
	var queryString = window.location.search.substring(1);
    var paramName = parameterName + "=";
    var begin;
    var end;
    if(queryString.length > 0){
        begin = queryString.indexOf(paramName);
        if(begin != -1){
            begin = begin + paramName.length;
            end = queryString.indexOf("&",begin);
            if(end == -1)
                            end = queryString.length;
            return queryString.substring(begin,end);
        }
    }
    return null;
}
function loadValues(){
	//var queryString = window.location.search.substring(1);
                
     //var wearLenses = getParameterValue1("b8_Wear_Lens");
     var product = getParameterValue1("b1_CVBrand_Interest");
	 var iframe = document.getElementById("free_trial_frame"); 
	 //var wearLenseField = iframe.contentWindow.document.getElementById("b8_Wear_Lens"); 
	 var productField = iframe.contentWindow.document.getElementById("a02_product"); 
	
	if(product == 'air-optix-aqua'){
		product = 'AIR OPTIX&reg; AQUA';
	}

	else if(product == 'air-optix-astigmatism'){
		product = 'AIR OPTIX&reg; ASTIGMATISM';
	}

	else if(product == 'air-optix-multifocal'){
		product = 'AIR OPTIX&reg; AQUA MULTIFOCAL';
	}

	else if(product == 'air-optix-night-and-day'){
		product = 'AIR OPTIX&reg; NIGHT &amp; DAY';
	}
	//wearLenseField.value=wearLenses;
	productField.value=product
	
	/*added by narayan*/
	var nProduct=getParameterValue1("b1_CVBrand_Interest");
	var prevLink = iframe.contentWindow.document.getElementById('ft_prev'); 
	var pProductModel = getParameterValue1("b2_Product_Modality");
	var pProductName = getParameterValue1("b3_Product_Name");

	/*added by onsite*/
	var productModalityField = iframe.contentWindow.document.getElementById("a03_Soft_Lens");
	productModalityField.value = pProductModel;
	var productNameField = iframe.contentWindow.document.getElementById("b3_Product_Name");
	productNameField.value = pProductName;


	prevLink.href=prevLink.href + '?product=' + nProduct + '&lensType=' + pProductModel + '&brand=' + pProductName;
}


//-------------------------------------------------------------------------------------------
// CLOSE THE WEBSITES DROP DOWN MENU
//------------------------------------------------------------------------------------------
function ddMenuClose()
{
	$('#nav').animate({ 
             height: "38px"
        }, 500); 

	$('#moreSites').animate({
	   opacity: 0
	}, 500).css("visibility","hidden");
}


//-------------------------------------------------------------------------------------------
// POSITION DIV IN THE CENTER OF WINDOW
//------------------------------------------------------------------------------------------
function centerLyr(divID)
{
    $('#'+divID).css("position","absolute");
 
    var newTop = ( $(window).height() - $('#'+divID).height() ) / 2+$(window).scrollTop();
    if(newTop<0) newTop = 0;

    var newLeft = ( $(window).width() - $('#'+divID).width() ) / 2+$(window).scrollLeft();
    if(newLeft<0) newLeft = 0;

    $('#'+divID).css("top", newTop + "px");
    $('#'+divID).css("left", newLeft + "px");
}

//-------------------------------------------------------------------------------------------
// RE-POSITION DIV IN THE CENTER OF WINDOW ON WINDOW RESIZE
//------------------------------------------------------------------------------------------
function rePositionLyr(status,divID) 
{
    switch(status) {
	case true:
		$(window).bind('resize', function() {
			centerLyr(divID);
		});
		//scroll is not used here
		//$(window).bind('scroll', function() {
		//	centerLyr(divID);
		//});
	    break;
	case false:
		$(window).unbind('resize');
		//scroll is not used here
		//$(window).unbind('scroll');
	    break;
    }
}

//-------------------------------------------------------------------------------------------
// POSITION OVERLAY IN THE CENTER OF WINDOW
//------------------------------------------------------------------------------------------
function showPopupDivCenter(divID) 
{
    if (scripts_isIE6) $('#'+divID).bgiframe();
    var toShow = $("#"+divID); 
    toShow.css({"z-index":"9000","visibility":"visible","display":"block"});
    centerLyr(divID);
    rePositionLyr(true,divID);
}

//-------------------------------------------------------------------------------------------
// OPEN DIV OVERLAY AND POSITION CENTER
//------------------------------------------------------------------------------------------
function openDivCenter(divID,closeBtnID)
{
    var toShow="";
    // Build the background overlay div
    toShow += "<div class='site_overlay'></div>";
    $('body').append(toShow);

    $('div.site_overlay').css('height',$(document).height()).bind('click',function(){
	closeDiv(divID);
	return false;
    });

    $('div.site_overlay').css('opacity',0).fadeTo('slow',0.65, function(){
	showPopupDivCenter(divID);
	$('div.site_overlay').css("z-index","9000");
	$('#'+divID).css("z-index","9500");
    });

    if(closeBtnID!=""){
        $("#"+closeBtnID).bind('click',function(){
	        closeDiv(divID);
		return false;
        });
    }
}

//-------------------------------------------------------------------------------------------
// CLOSE OPENED DIV OVERLAY
//------------------------------------------------------------------------------------------
function closeDiv(divID)
{
    $('div.site_overlay').remove();
    rePositionLyr(false,divID);
    var toHide = $("#"+divID); 
    toHide.css({"z-index":"0","visibility":"hidden"});
    if(divID=="all-products"){
	toHide.css("width", "1px");
	toHide.css("height", "1px");
    }
    soundOn();
    
    if(divID=="tv-ads-overlay")
    {
		$('#swfTVSpot').remove();
		$('#flashcontent').remove();
		$("#tv-ads-overlay").children("div.lyrRel").append("<div id='flashcontent'></div>");
    }
}


//-------------------------------------------------------------------------------------------
// GOOGLE PAGE & EVENT TRACKING FUNCTIONS
//------------------------------------------------------------------------------------------

function ga_trackEvent(category, action, optional_label)
{
   try { 
	//alert("tracking event: "+category+" > "+action+" > "+optional_label);

	pageTracker._trackEvent(category, action, optional_label);

   } catch(err) {}
}

function ga_trackPage(pageName)
{
   try { 
	//alert("tracking page view: "+pageName);
	pageTracker._trackPageview(pageName);
   } catch(err) {}
}

function ga_getExternalLinkName(url)
{
   var str = url;
   str = str.replace(/http:\/\//i, "");
   str = str.replace(/www\./i, "");
   str = "External_URL_"+str;
   return str;
}

function ga_pageTracker(url)
{
    var pageName = ga_getExternalLinkName(url);
    ga_trackPage(pageName);
}

