$(document).ready(function() {
/* - IN THE HEAD OF THE TEMPLATE NOW - Chad 6-2-11
    // File Downloads Tracking
    $('a').click(function(e) {
      var types = new Array('.pdf','.doc','.xls','.ppt','.docx','.xlsx','.pptx','.txt','.csv','.rtf','.zip');
      href = $(this).attr('href');
      if(href!="#") {
	  	filename = href.split("/");
        for(var x in types) {
          srch = new RegExp(types[x],"g");
          if (srch.test(filename)) {
              //alert('Track file: '+ filename[parseInt(filename.length)-1]);
              gaTrackEvent('Files','Download',filename[parseInt(filename.length)-1]);
          }
        }
	  }
    });
*/
    
    $('a#non-flash-reel').click(function() {
    	displayReel();        
    });

    $('a#non-flash-close-reel').click(function() {
        closeReel();
    });
    
    // select all the a tag with name equal to modal
    $('a[name=modal]').click(function(e) {
        // Cancel the link behavior
        e.preventDefault();
    });

    // MODAL WINDOW CONTROLS
    // if close button is clicked
    $('.window .close').click(function(e) {
        if ($(this).hasClass('go') == false) {
            // Cancel the link behavior
            e.preventDefault();
        }

        $('#mask, .window').hide();
    });

    // if mask is clicked
    $('#mask').click(function() {
        $(this).hide();
        $('.window').hide();
    });

    // Sales request form processing
    $('a.salesRequest').click(function(e) {
        e.preventDefault();
        launchWindow('modalSalesFormWin');
    });

    $('form#form-sales-request').submit(function(e) {
        e.preventDefault();
        $.ajax( {
            type : 'post',
            url : '/salesRequest',
            data : {
                company : $('#company').val(),
                contact_person : $('#contact_person').val(),
                phone : $('#phone').val(),
                email : $('#email').val(),
                product_of_interest : $('#product_of_interest').val(),
                comments : $('#comments').val(),
                email_signup :  (($('#email-signup').is(':checked')) ? 'on': 'off')
            },
            dataType : 'json',
            success : function(msg) {
                if (msg.status == 'OK') {   
                    $('#sales-request').html(msg.response);
                    $('#modalSalesFormWin').center();
                    gaTrackEvent('Forms','Submission','Sales Request Submitted');
                } else {
                    // Remove any previous errors
                    $('span').removeClass('error');

                    // Hide invalid-email-error
                    $('#invalid-email-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') {
                            $('#'+index+'-error').addClass('error');
                            $('#invalid-email-error').addClass('error');
                            $('#invalid-email-error').html('('+value+')');
                            $('#invalid-email-error').show();
                        } else {
                            $('#'+index+'-error').addClass('error');
                        }
                    });
                    var txt = '<p>Please be sure you have filled out all required fields.</p>';
                    $('#form-sales-request-error').html(txt);
                    $('#modalSalesFormWin').center();
                }
            }
        });
    });
    
    //Hide (Collapse) the toggle containers on load
    //$("#social").hide(); 

    //Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
    $("#link-share-DISABLED").click(function(){
        $('#social').animate({
            width: 'toggle'
        }, 1000);
        return false;
    });

    $("#mobile-about").click(function(e){
        e.preventDefault();
        $('#menu-ct').animate({
            height: 'toggle'
        }, 50);
        $('#mobile-about').css("display", "none");
        $('#mobile-menu-close').css("display", "block");
        $("#header").expose({
            color: '#000',
            opacity: '0.5',
            onBeforeLoad: function(){
                this.getMask().appendTo('body');
            }
        });
    });
    
    $("#mobile-menu-close").click(function(e){
        e.preventDefault();
        $('#menu-ct').animate({
            height: 'toggle'
        }, 50);
        $.mask.close();
        $('#mobile-menu-close').css("display", "none");
        $('#mobile-about').css("display", "block");
    });

    // Get Social Tab
    $("#social-media-toolbar #toolbar-tab a").click(function(e) {
        e.preventDefault();
        toggleSMT();
    });

    $("#social-media-toolbar a#hide-bar").click(function(e) {
        e.preventDefault();
        hideSMT();
    });
});

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

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) {

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

    var sizes = [ 'small', 'medium', 'large' ];

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

    var body = document.getElementsByTagName('body')[0];

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

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

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

    body.className = body.className.replace('/ ' + current_font_size + '/', '');

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

    body.className = ' ' + font_size;

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

    document.cookie = 'font_size=' + font_size + ';path=/;';

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

};

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

var hbx = undefined;

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

Zoomedia.Form = new function() {

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

    this.submit = function(form) {
        if (hbx != undefined) {
            hbx.pn += '+FORM+SUBMIT';
        }
        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

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

// LoadPlayer JS
function loadPlayer(id, moviepath, width, height){		
	
	var html5type = "mp4";
	if ($.browser.webkit) {
		html5type = "mp4";
	}
	if ($.browser.mozilla) {
		html5type = "ogv";
	}
	
	var hasFlash = swfobject.getFlashPlayerVersion();
	if (hasFlash.major > 0) {
		
		// Set the swfobject data
	    params = {};
	    params.quality = 'high';
	    params.wmode = 'opaque';
	    params.salign = 't';
	    params.allowFullScreen = true;
	    vars = {};
	    vars.moviepath = moviepath;
	    swfobject.embedSWF("/video/ZoomediaLib-PlayerFlash-R1.swf", id, width, height, "8", "/js/expressInstall.swf", vars, params);
		
	    
	} else {
						
		$('#'+id).html('<div id="non-flash-html5"><video id="non-flash-video" controls="controls" width="640" height="480"  preload="auto"><source id="webkit-movie" src="'+moviepath+'" /></video></div>');
   		document.getElementById('non-flash-video').play();	
	}
   
}


// jQuery mod functions
jQuery.fn.center = function() {
    var top = (($(window).height() - this.height()) / 2)
    + $(window).scrollTop();
    var left = (($(window).width() - this.width()) / 2)
    + $(window).scrollLeft();
    this.css('position', 'absolute');
    this.css('top', top);
    this.css('left', left);

    return this;
}

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

// Modal Window functions
function launchWindow(id) {
    id = "#" + id;
    // Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    // Set heigth and width to mask to fill up the whole screen
    $('#mask').css( {
        'width' : maskWidth,
        'height' : maskHeight
    });

    // transition effect
    $('#mask').fadeTo("slow", 0.6);
    $('#mask').fadeIn(500);

    $(id).center();

    // transition effect
    $(id).fadeIn(2000);
}

var version = swfobject.getFlashPlayerVersion();

function lightsOut(){

    $("#video-container").expose({
        color: '#000',
        onBeforeLoad: function(){
            this.getMask().appendTo('body');
        }
    });
	
}

function displayReel() {
	params = {};
    params.quality = 'high';
    params.wmode = 'transparent';
    params.allowFullScreen = 'true'; 
    params.salign = 't';

    vars = {};
    vars.moviepath = "/video/zoomedia_demo_reel_2011.mp4";
    
    if(version.major > 0) {
        swfobject.embedSWF("/swf/Zoomedia-PlayerFlash-R1.swf", "flash-reel", "1005", "590", "8", false, vars, params);
    } else {
        document.getElementById('non-flash-reel-video').play();
    }
    
    $('#flash-home-container').animate({
        height: '630px'
    });
    $('#flash-home').fadeOut('fast', function() {
        $('#non-flash-html5').fadeIn('fast');
    });
}

function closeReel() {
	if (version.major > 0) {
        $('#flash').html('<div id="flash-reel"></div>');
        $('#flash-home').fadeIn('fast');
    } else {
        document.getElementById('non-flash-reel-video').pause();
        $('#non-flash-html5').fadeOut('fast', function() {
            $('#flash-home').fadeIn('fast');
        });
    }

    $('#flash-home-container').animate({
        height: '261px'
    });
}

// GET SOCIAL FUNCTIONS
function toggleSMT() {
    // I'll animate my content closed
    $("#social-media-toolbar .content").animate({
        "height": "toggle"
    }, 500);

    // Class-setting logic: If I was open before, I must be closed now
    if ($("#social-media-toolbar").hasClass("open")) {
        $("#social-media-toolbar").attr("class","hidden");
        twitterWidget.stop();
    }

    // Class-setting logic: If I was closed (or hidden) before, I must be open now
    else {
        $("#social-media-toolbar").attr("class","open");
        twitterWidget.start();
    }
}

function hideSMT() {
    // If the user wants to hide me:
    // I'll hide my content, I'll put a "hidden" class on myself, and I'll remember to stay discreet
    $("#social-media-toolbar").attr("class", "hidden");
    $("#social-media-toolbar .content").css("display","none");
    twitterWidget.stop();
}


(function($){
    $.fn.cloudinizr = function(options) {
        var opts = $.extend({
            loPerc: 100,
            hiPerc: 150
        },options);

        return this.each(function(){
            var _arry = $(this).html().toLowerCase()
            .replace(/<[^>]+>|[,?.'"!;:]/g,'')
            .replace(/[-\n\t ]/g,' ').split(' ');

            var _tags={}, _s='', _min=1000, _max=0;

            for (var i=0;i<_arry.length;i++) {
                if (_arry[i].match(/^(.{0,3}|\d+)$/)) continue;
                var c = _tags[_arry[i]] = (_tags[_arry[i]] || 0) + 1;
                _min = (c > _min) ? _min : c;
                _max = (c < _max) ? _max : c;
            }

            var _m=(opts.hiPerc-opts.loPerc)/(_max-_min);
            $(this).empty();
            for (var word in _tags)
                $(this).append('<span title="'+
                    _tags[word]+'" style="font-size: '+
                    (opts.loPerc + ((_max-(_max-(_tags[word]-_min)))*_m))+
                    '%">'+word+'<\/span> ')
        });
    };
})(jQuery);


