
// --------------------------------------------------------------------------

Zoomedia = {

    version: '1.0',
    
    redirect: function(url){
        var anchor_pos = url.indexOf("#");
        document.location.href = (anchor_pos == -1) ? url : url.substr(0, anchor_pos);
    },
    
    print: function(){
        if (window.print) {
            window.print();
        }
        else {
            alert("Sorry, your browser doesn't support this feature.\nPlease use your browser's print button");
        }
        return false;
    }
};

// --------------------------------------------------------------------------

Zoomedia.Menu = function(id){
    if (id) {
        try {
            this.build(document.getElementById(id));
        } 
        catch (err) {
        }
    }
};

// --------------------------------------------------------------------------

Zoomedia.Menu.prototype = {

    // ------------------------------------------------------------------------
    
    ptr: null,
    timer: null,
    delay: 1000,
    liList: [],
    
    // ------------------------------------------------------------------------
    
    setTimeOut: function(el){
        var self = this;
        var id = el.getAttribute('id');
        this.timer = window.setTimeout(function(){
            self.mouseOut(document.getElementById(id));
        }, this.delay);
    },
    
    // ------------------------------------------------------------------------
    
    mouseOut: function(el){
        if (this.timer != null && this.ptr != null && this.ptr.id == el.id) {
            if (!el.firstChild.getAttribute('on')) {
                el.firstChild.className = '';
            }
            
            for (var ulList = el.getElementsByTagName('ul'), i = 0; i < ulList.length; ++i) {
                ulList.item(i).style.visibility = 'hidden';
            }
            
            for (var liList = el.getElementsByTagName('li'), i = 0; i < liList.length; ++i) {
                liList.item(i).firstChild.className = '';
            }
            
            this.ptr = null;
            this.liList = new Array();
            
            return;
        }
        
        var className = '';
        for (var i = 0; i < this.liList.length; i++) {
            if (this.liList[i] == el.id) {
                className = 'hover';
                break;
            }
        }
        
        if (!el.firstChild.getAttribute('on')) {
            el.firstChild.className = className;
        }
    },
    
    // ------------------------------------------------------------------------
    
    mouseOver: function(el){
        for (var i = 0; i < this.liList.length; ++i) {
            if (this.liList[i] == el.id) {
                break;
            }
        }
        
        if (i == this.liList.length) {
            this.liList[i] = el.id;
        }
        
        if (this.timer != null && this.ptr != null) {
            if (!this.ptr.firstChild.getAttribute('on')) {
                this.ptr.firstChild.className = '';
            }
            for (var ulList = this.ptr.getElementsByTagName('ul'), i = 0; i < ulList.length; ++i) {
                ulList.item(i).style.visibility = 'hidden';
            }
            window.clearTimeout(this.timer);
            this.timer = null;
            this.liList = new Array();
        }
        
        this.ptr = el;
        
        if (this.ptr.tagName.toLowerCase() == 'li') {
            if (!this.ptr.firstChild.getAttribute('on')) {
                this.ptr.firstChild.className = 'hover';
            }
        }
        
        var ulList = this.ptr.getElementsByTagName('ul');
        
        if (ulList.length > 0) {
            ulList.item(0).style.visibility = 'visible';
        }
    },
    
    // ------------------------------------------------------------------------
    
    build: function(el){
        var self = this;
        for (var i = 0; i < el.childNodes.length; ++i) {
            if (el.childNodes[i].nodeName.toLowerCase() == 'li') {
                for (var j = 0; j < el.childNodes[i].childNodes.length; ++j) {
                    if (el.childNodes[i].childNodes[j].nodeName.toLowerCase() == 'ul') {
                        el.childNodes[i].onmouseover = function(){
                            try {
                                self.mouseOver(this);
                            } 
                            catch (err) {
                            }
                        };
                        el.childNodes[i].onmouseout = function(){
                            try {
                                self.setTimeOut(this);
                            } 
                            catch (err) {
                            }
                        };
                        //this.build(el.childNodes[i].childNodes[j]);
                        //break;
                    }
                }
            }
        }
    }
    
    // ------------------------------------------------------------------------

}//Zoomedia.Menu
// --------------------------------------------------------------------------

Zoomedia.Glossary = new function(){

    // ------------------------------------------------------------------------
    
    this.current = null;
    
    // ------------------------------------------------------------------------
    
    this.items = {};
    
    // ------------------------------------------------------------------------
    
    this.tpl = '<div class="glossary">' +
    '<div class="header">%POPUP_TITLE%</div>' +
    '<div class="main">%POPUP_CONTENT%</div>' +
    '<div class="footer"><a href="#" onclick="Zoomedia.Glossary.hide(\'div_%GLOSSARY_ID%\'); return false;">close</a></div>' +
    '</div>';
    
    // ------------------------------------------------------------------------
    
    this.setItems = function(items){
        this.items = items;
    };
    
    // ------------------------------------------------------------------------
    
    this.show = function(a, id, event){
        if (this.current) {
            this.hide(this.current);
        }
        
        var div = document.createElement('div');
        div.setAttribute('id', 'div_' + id);
        div.onclick = function(){
            Zoomedia.Glossary.hide('div_' + id);
        };
        div.className = 'gloss_def';
        div.style.position = 'absolute';
        div.style.display = 'none';
        div.style.zIndex = 2000;
        
        /*offset = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
         if (!offset) {
         offset = 0; // stupid ie5/mac
         }
         div.style.top = (offset + event.clientY)+'px';
         div.style.left = event.clientX+'px';*/
        div.innerHTML = this.tpl.replace('%GLOSSARY_ID%', id).replace('%POPUP_TITLE%', this.items[id].title).replace('%POPUP_CONTENT%', this.items[id].content);
        
        //insert div before anchor tag
        a.parentNode.insertBefore(div, a);
        
        div.style.top = (a.offsetTop - a.clientHeight - div.clientHeight) + 'px';
        div.style.left = a.offsetLeft + 'px';
        div.style.display = 'block';
        
        this.current = 'div_' + id;
        
        //close removes the dynamically created div
        //div.parentNode.removeChild(div);
    };
    
    // ------------------------------------------------------------------------
    
    this.hide = function(eleId){
        var div = document.getElementById(eleId);
        if (div) {
            div.parentNode.removeChild(div);
        }
    };
    
    // ------------------------------------------------------------------------

};

// --------------------------------------------------------------------------

Zoomedia.FontSize = function(font_size){

    // Write the text images
    $("a#textsmall").css("background-position", "0px 0px");
    $("a#textmed").css("background-position", "0px 0px");
    $("a#textlarge").css("background-position", "0px 0px");
    
    if (font_size == "small" || !font_size) {
        $("a#textsmall").css("background-position", "0px -16px");
    }
    if (font_size == "medium") {
        $("a#textmed").css("background-position", "0px -16px");
    }
    if (font_size == "large") {
        $("a#textlarge").css("background-position", "0px -16px");
    }
    
    // ------------------------------------------------------------------------
    
    var sizes = ['small', 'medium', 'large'];
    
    // ------------------------------------------------------------------------
    
    var body = document.getElementById('wrapper');
    
    // ------------------------------------------------------------------------
    
    var current_font_size = 'medium';
    
    // ------------------------------------------------------------------------
    
    var match = document.cookie.match(/(?:font_size=(.+)(?:;?|$))/);
    
    // ------------------------------------------------------------------------
    
    if (match) {
        current_font_size = match[1];
        if (font_size == current_font_size) {
            //return;
        }
    }
    
    // ------------------------------------------------------------------------
    
    if (body) {
    
        body.className = body.className.replace('/ ' + current_font_size + '/', '');
        
        body.className = ' ' + font_size;
        
    }
    
    // -----------------------------------------------------------------------
    
    document.cookie = 'font_size=' + font_size + ';path=/;';
    
};

function getCookie(c_name){
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) 
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return false;
}

// --------------------------------------------------------------------------

Zoomedia.Form = new function(){

    // ------------------------------------------------------------------------
    
    this.submit = function(form){
        document.getElementById(form).submit();
    };
    
    // ------------------------------------------------------------------------
    
    this.formatNumber = function(value){
        return value.replace(/[^\d.]/g, '');
    };
    
    // ------------------------------------------------------------------------
    
    this.formatTelephoneNumber = function(value){
        return value.replace(/[^\d]/g, '');
    };
    
    // ------------------------------------------------------------------------

};

// --------------------------------------------------------------------------

Zoomedia.SharePage = new function(id){

    // ------------------------------------------------------------------------
    
    this.timer = null;
    
    // ------------------------------------------------------------------------
    
    this.delay = 500;
    
    // ------------------------------------------------------------------------
    
    this.active = false;
    
    // ------------------------------------------------------------------------
    
    this.setActive = function(enabled){
        this.active = enabled;
    };
    
    // ------------------------------------------------------------------------
    
    this.isActive = function(){
        return this.active;
    };
    
    // ------------------------------------------------------------------------
    
    this.setTimeOut = function(el){
        var self = this;
        var id = el.getAttribute('id');
        this.timer = window.setTimeout(function(){
            self.mouseOut(document.getElementById(id));
        }, this.delay);
    };
    
    // ------------------------------------------------------------------------
    
    this.hide = function(el){
        this.setActive(false);
        document.getElementById('share-page-widget').style.display = 'none';
    };
    
    // ------------------------------------------------------------------------
    
    this.show = function(a){
        //if (this.isActive()) {
        //return;
        //}
        
        this.setActive(true);
        
        var widget = document.getElementById('share-page-widget');
        if (widget) {
            widget.style.top = (a.offsetTop + a.offsetHeight) + 'px';
            widget.style.left = a.offsetLeft + 'px';
            widget.style.display = 'block';
        }
        
        return false;
    };
    
    // ------------------------------------------------------------------------

}; //Zoomedia.SharePage
// --------------------------------------------------------------------------

function productFamilySearch(term){
    term = term.replace('/', '+');
    window.location = '/search/productfamily/' + escape(term);
}
function productProcedureSearch(term){
    term = term.replace('/', '+');
    window.location = '/search/productprocedure/' + escape(term);
}
function productSearch(term){
    term = term.replace('/', '+');
    window.location = '/search/products/' + escape(term);
}


function handleSendToSubmit(e, submitto){

    //e.preventDefault();
    $.ajax({
        type: 'post',
        url: submitto,
        data: {
            fname: $('#fname').val(),
            lname: $('#lname').val(),
            email: $('#email').val(),
            optin: (($('#optin').is(':checked')) ? 'on' : 'off'),
            friendname: $('#friendname').val(),
            friendemail: $('#friendemail').val(),
            howheard: $('#howheard').val(),
            resource_key: $('#resource_key').val()
        },
        dataType: 'json',
        success: function(msg){
            if (msg.status == 'OK') {
                $('#popup_content').html(msg.response);
				_hbPageView('success','/index'+submitto);
                // $('#popup_container').center();
            }
            else {
                // Remove any previous errors
                $('span').removeClass('error');
                
                // Hide invalid-email-error
                $('#invalid-email-error').hide();
                $('#invalid-friendemail-error').hide();
                
                // Loop through all errors
                $.each(msg.response, function(index, value){
                    // Display invalid email address if set
                    if (index == 'email' && value == 'Invalid Email Address') {
                        $('#email-label').addClass('error');
                        $('#invalid-email-error').addClass('error');
                        $('#invalid-email-error').html('(' + value + ')');
                        $('#invalid-email-error').show();
                    }
                    else 
                        if (index == 'friendemail' && value == 'Invalid Email Address') {
                            $('#friendemail-label').addClass('error');
                            $('#invalid-friendemail-error').addClass('error');
                            $('#invalid-friendemail-error').html('(' + value + ')');
                            $('#invalid-friendemail-error').show();
                            
                        }
                        else {
                            $('#' + index + '-label').addClass('error');
                        }
                });
                var txt = '<p class="error">Please be sure you have filled out all required fields.</p>';
                $('#send_dr_search-error').html(txt);
                // $('#popup_container').center();
            }
        }
    });
}


function handleSendToDrSubmit(e, submitto){

    //e.preventDefault();
    $.ajax({
        type: 'post',
        url: submitto,
        data: {
            fname: $('#fname').val(),
            lname: $('#lname').val(),
            address1: $('#address1').val(),
            address2: $('#address2').val(),
            city: $('#city').val(),
            state: $('#state').val(),
            zip: $('#zip').val(),
            phone: $('#phone').val(),
            email: $('#email').val(),
            optin: (($('#optin').is(':checked')) ? 'on' : 'off'),
            patient: $('#patient').val(),
            timeframe: $('#timeframeMonth').val() + ' ' + $('#timeframeYear').val(),
            comments: $('#comments').val(),
            howheard: $('#howheard').val(),
            resource_key: $('#resource_key').val()
        },
        dataType: 'json',
        success: function(msg){
            if (msg.status == 'OK') {
                $('#popup_content').html(msg.response);
                // $('#popup_container').center();
            }
            else {
                // Remove any previous errors
                $('span').removeClass('error');
                
                // Hide invalid-email-error
                $('#invalid-email-error').hide();
                $('#invalid-friendemail-error').hide();
                
                // Loop through all errors
                $.each(msg.response, function(index, value){
                    // Display invalid email address if set
                    if (index == 'email' && value == 'Invalid Email Address') {
                        $('#email-label').addClass('error');
                        $('#invalid-email-error').addClass('error');
                        $('#invalid-email-error').html('(' + value + ')');
                        $('#invalid-email-error').show();
                    }
                    else 
                        if (index == 'friendemail' && value == 'Invalid Email Address') {
                            $('#friendemail-label').addClass('error');
                            $('#invalid-friendemail-error').addClass('error');
                            $('#invalid-friendemail-error').html('(' + value + ')');
                            $('#invalid-friendemail-error').show();
                            
                        }
                        else {
                            $('#' + index + '-label').addClass('error');
                        }
                });
                var txt = '<p class="error">Please be sure you have filled out all required fields.</p>';
                $('#send_dr_search-error').html(txt);
                // $('#popup_container').center();
            }
        }
    });
}


function vettDrSearchSubmit(formname){
    $('#error-row-zip').hide();
    $('#error-row-city').hide();
    
    if (formname == 'zip') {
        var zip_len = $('#zipcode').val().length;
        
        if ((zip_len < 4) || ($('#zipcode').val() == 'Enter Zip Code')) {
            $('#error-row-zip').show();
            return false;
            
        }
        else {
            var outp = false;
            $.ajax({
                type: 'post',
                async: false,
                url: '/physician_finder_actions/checkzip',
                data: {
                    zip: $('#zipcode').val(),
                    country_code: 'USA'
                },
                dataType: 'json',
                success: function(msg){
                    if (msg.status == 'OK') {
                        outp = true;
                        
                    }
                    else {
                        $('#error-row-zip').show();
                        outp = false;
                    }
                }
            });
            return outp;
        }
    }
    
    if (formname == 'city') {
        var state_len = $('#state').val().length;
        if (state_len == 0) {
            $('#error-row-city').show();
            return false;
        }
        return true;
    }
    
    return false;
}


function loadPlayer(title, desc, id, transpath){

	// Reset the HTML data
	//$('html head title').html('');
	$('#video-description-header h3.title').html('');
	$('#video-description-text').html('');
	// Set the new content
	//$('html head title').html('ArthroCare ENT: ' + title);
	$('#video-description-header h3.title').html(title);
	$('#video-description-text').html(desc);
	
	if(/\/video_library\//.test(window.location)) {
		$('#masthead-inner h1').html('');
	    $('#breadcrumb span.current-page').html('');
	    $('#masthead-inner h1').html(title);
	    $('#breadcrumb span.current-page').html(title);
	}
	
	
	var html5type = "mp4";
	if ($.browser.webkit) {
		html5type = "mp4";
	}
	if ($.browser.mozilla) {
		html5type = "ogv";
	}
	
	var movie;
	var moviepath;
	var hasFlash = swfobject.getFlashPlayerVersion();
	if (hasFlash.major > 0) {
		
		$.get('/ajaxGetVideo?id='+id+'&type=mp4', function(data) {
			movie = data.filename;
			moviepath = '/movies/'+ id +'/'+ movie;
			// Set the swfobject data
		    params = {};
		    params.quality = 'high';
		    params.wmode = 'opaque';
		    params.salign = 't';
		    params.allowFullScreen = true;
		    vars = {};
		    vars.moviepath = moviepath;
		    vars.transpath = transpath;
		    swfobject.embedSWF("/swf/ArthroCareENT-ProductWebsite-PlayerFlash-R1.swf", "video-player", "674", "389", "8", "/js/expressInstall.swf", vars, params);
		});
	    
	} else {
		$.get('/ajaxGetVideo?id='+id+'&type='+html5type, function(data) {
			movie = data.filename;
			moviepath = '/movies/'+ id +'/'+ movie;
			$('#video-player').html('<div id="non-flash-html5"><video id="non-flash-reel-video" controls="controls" width="638" height="358"  preload="auto"><source id="webkit-movie" src="'+moviepath+'" /></video></div>');
	   		document.getElementById('non-flash-reel-video').play();		
		});	   	
	}
	
	$('#video-player').css('height', '389px');
   
}

 // EXACT TARGET FORMS
function etForms(form) {
	$.ajax({
        type: 'post',
        url: '/' + form,
        data: {
            fname: $('#'+ form + ' #fname').val(),
            lname: $('#'+ form + ' #lname').val(),
            email: $('#'+ form + ' #email').val()
        },
        dataType: 'html',
        success: function(msg){
			$('#popup_content').html(msg);
        }
    });
}


function lightsOut(){
	if($.mask.isLoaded() == 'full') {
		$.mask.close();
	} else {
		$("#video-container").expose({
	        color: '#000',
	        onBeforeLoad: function(){
	            this.getMask().appendTo('body');			
	        }
	    });
	}    
}

function gaTrackUrl(url) {
 _gaq.push(['_trackPageview', url]);
}
function gaTrackEvent(category,event,title) {
 _gaq.push(['_trackEvent', category, event, title]);
}


// --------------------------------------------------------------------------

$(document).ready(function(){
	
	// Location list
	$('a#location-list-link, ul#location-list a.selected').click(function() {
		$('ul#location-list li.hidden').toggle('fast');
	});
	$('ul#location-list li a#location-us:not(.selected)').click(function(e) {
		e.preventDefault();
		$.cookie('artcLocation','en');
		if($.cookie('disclaimer') != 'no-remind') {
            launchWindow('#modalFormWin');
        } else {
            window.location = $(this).attr('href');
        }
		$('#modalFormWin #disclaimerSubmit').attr('action', $(this).attr('href'));
	});
	$('ul#location-list li a#location-es:not(.selected)').click(function(e) {
		e.preventDefault();
		$.cookie('artcLocation','es');
		if($.cookie('disclaimer') != 'no-remind') {
            launchWindow('#modalFormWin');
        } else {
			window.location = $(this).attr('href');
		}
        $('#modalFormWin #disclaimerSubmit').attr('action', $(this).attr('href'));
	});
	$('ul#location-list li a#location-uk:not(.selected)').click(function(e) {
		e.preventDefault();
		$.cookie('artcLocation','int');
		if($.cookie('disclaimer') != 'no-remind') {
			launchWindow('#modalFormWin');
		} else {
            window.location = $(this).attr('href');
        }
        $('#modalFormWin #disclaimerSubmit').attr('action', $(this).attr('href'));
	});
	$('#disclaimerSubmit input#send').click(function() {
		if($('#disclaimerSubmit #checkbox-container input:checked').length > 0) {
			$.cookie('disclaimer','no-remind');
		}
	});
	
	// PRODUCT SEARCH FORM ACTIONS
    $('#form-browse-product #browse-product').change(function(){
        productFamilySearch($(this).val());
    });
    $('#form-browse-procedure #browse-procedure').change(function(){
        productProcedureSearch($(this).val());
    });
    $('form#form-search-keywords').submit(function(e){
        e.preventDefault();
        var terms = $('input#form-search-terms').val();
        productSearch(terms);
    });
    
    // MODAL WINDOW ACTIONS
    $('a[name=modal]').click(function(e){
        // Cancel the link behavior
        e.preventDefault();
        launchWindow($(this).attr('href'));
    });
    
    $('a.poplight[href^=#]').click(function(e){
        // Cancel the link behavior
        e.preventDefault();
        launchPopWindow(this);
    });
    
    // MODAL WINDOW CONTROLS
    // if close button is clicked
    $('.window .close, #popup_container .close').click(function(e){
        if ($(this).hasClass('go') == false) {
            // Cancel the link behavior
            e.preventDefault();
        }
        
        $('#mask, .window').hide();
    });
    $('#popup_container a.close').click(function(e){
        e.preventDefault();
        $('#popup_container').fadeOut();
    });
    
    $('a.closePop, #fade').live('click', function(e){ //When clicking on the close or fade layer...
        e.preventDefault();
        $('#fade , .popup_block').fadeOut(function(){
            $('#fade, a.close').remove(); //fade them both out
        });
    });
        
    // Init tabs
    $("#tabs").tabs();
    
    //Hide (Collapse) the toggle containers on load
    //$("#social").hide();
    
    $("#link-share").click(function(){
        $('#social').slideToggle('normal');
    });
    
    // State selected in Dr Finder
    if ($("select#state").val() != '' && $("select#topics").val() == '') {
        loadDoc(document.getElementById('state'));
    }
	
	$("#container ul.submenu li:first-child").addClass("firstChild");
    
    // VIDEO VIEWER
    // Show/Hide Video Descriptions
    $('#description-link').click(function(){
        $('#description-link').css("display", "none");
        $('#video-description-text').slideToggle('slow', function(){
            $('#description-close').css("display", "inline");
        });
    });
    $('#description-close').click(function(){
        $('#description-close').css("display", "none");
        $('#video-description-text').slideToggle('slow', function(){
            $('#description-link').css("display", "inline");
        });
    });
    
    $('#videocarousel a').click(function(e){
        e.preventDefault();
        $('#videocarousel a').removeClass("on");
        $(this).addClass("on");
    });
    
    $('#videocarousel').jcarousel({
        scroll: 1,
        itemFallbackDimension: 143
    });
	
	$("#video-carousel .jcarousel-skin-tango .jcarousel-next-horizontal").hover(function(){
        $(this).css("background-position", "0 -13px");
    }, function(){
        $(this).css("background-position", "0 0");
    });
    
    $("#video-carousel .jcarousel-skin-tango .jcarousel-prev-horizontal").hover(function(){
        $(this).css("background-position", "0 -13px");
    }, function(){
        $(this).css("background-position", "0 0");
    });
    
    // IMAGE VIEWER
    // Transition from image thumbs to full image view		
    $('#thumb-list a').click(function(e){
        e.preventDefault();
        var thumbIndex = ($('#thumb-list a').index(this) + 1);
        $('#image-thumbs').fadeOut('fast', function(){
            $('#imagecarousel').jcarousel({
                scroll: 1,
                itemFallbackDimension: 674,
                start: thumbIndex
            });
            $('#image-viewer').fadeIn('fast');
            $('#image-viewer').css("visibility", "visible");
            $('#image-viewer').css("height", "auto");
			if($("#imagecarousel > li").size() < 2) {
				$('#image-carousel .jcarousel-prev-horizontal, #image-carousel .jcarousel-next-horizontal').css('visibility','hidden');
			}
        });
    });
    
    // Transition from full image view to image thumbs
    $('#image-viewer a#image-close').click(function(e){
        e.preventDefault();
        $('#image-viewer').fadeOut('fast', function(){
            $('#image-thumbs').fadeIn('fast');
        });
        
    });    
    
});



