﻿var _historyArr = new Array();
var _arrCount = 0;
var _javaUploader = '/tinna/upload/files/templates/uploader/';
var _permalink = false;

function goBack() {
    ReplaceContent("body_container", _historyArr[_historyArr.length-2], false);
    _historyArr[_historyArr.length-1] = null;
    _historyArr.length--;
}

function ShowObject(elementId) {
    var object = null;
    
    if(typeof(elementId) == "string") {
        object = document.getElementById(elementId);
    } else {
        object = elementId;
    }
        
    if(object) {
        if(object.className.indexOf(" hide") > -1) {
            object.className = object.className.replace(" hide","");
        } else if(object.className.indexOf("hide") > -1) {
            object.className = object.className.replace("hide","");
        }
        
        if(object.style.display == 'none') {
            object.style.display = '';
        }
    }
}

function HideObject(elementId) {
    var object = null;
    
    if(typeof(elementId) == "string") {
        object = document.getElementById(elementId);
    } else {
        object = elementId;
    }   

    if(object) { 
        if(object.className.indexOf("hide") == -1) { 
            if(object.className.length > 0) {
                object.className += " hide";
            } else {
                object.className = "hide";
            }
        }
    }
}

function ReplaceContent(elementId, text, history) {
    var obj = document.getElementById(elementId);
    
    if(obj) {
        if(history == undefined || history) {
            _historyArr[_historyArr.length] = text;
        }
        
        obj.innerHTML = text;
    }    
}

function GetMenu() {
    $("#menu_container").load("/Home/Menu");
}

function Login() {
    var user = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    showUpdate("Logging in...");

    jQuery.post("/Home/Authenticate", { user: user, password: password }, function () {
        GetMenu();
        stopUpdateWindow();
        ReplaceContent("body_container", "Successfully logged in.");
    });
}

function Logout() {
    jQuery.post("/Home/Logout", function () {
        document.location.href = "/";
    });
}

/** gallery **/
var _tags = "";

function GetImageCloud() {
    showUpdate("Please wait, fetching images...");
    _tags = "";

    jQuery.post("/Home/GetImageCloud", null, function (data) {
        var html = '<h2>Image cloud</h2>';
        html += '<p class="tooltip">Search for the image you want</p>';
        html += '<p class="image-help"><a href="javascript:ImageHelp()">Need help?</a></p>';
        html += '<div class="help hide" id="image-help"><p>The image cloud is a search/filtering application, which helps you find exactly the image you want by filtering all the images by "tags".<br/><br/>';
        html += 'So what are tags? Tags are like keywords, and those are the words you see splashed around below in a seemingly random sized manner. But it\'s actually not random, the bigger the word, the more images are available that match that tag.<br/><br/>';
        html += 'If you click on any tag, the system will search for images that have that particular tag attached to them, and bring you the results. In the results page you can:<br/><br/>';
        html += '1. Click on an image name to view the image.<br/>';
        html += '2. Show/hide thumbnails of all image results for a quick viewing.<br/>';
        html += '3. Click on a second tag (or third or forth etc) to filter the current list even further.<br/>';
        html += '4. Click on an already selected tag (in the "Filtering by" list at the top), and thus removing that filter, in case you need to widen the search again.</p></div>';
        html += '<ul class="image_cloud">';

        for (var i = 0; i < data.length; i++) {
            html += '<li style="font-size:' + (data[i].Size) + '%"><a onclick="LimitImages(\'' + data[i].Name + '\')" href="#cloud:' + data[i].Name + '" title="Search for images tagged with: ' + data[i].Name + '">' + data[i].Name + '</a></li>';
        }
    
        html += '<div class="clear"></div></ul>';
        stopUpdateWindow();
        ReplaceContent("body_container", html);
    }, "json");
}

function ImageHelp() {
    var help = document.getElementById("image-help");
    
    if(help.className.indexOf("hide") > -1) {
        ShowObject(help);
    } else {
        HideObject(help);
    }
}

function GetTagFilters() {
    var tags = _tags.split(",");
    
    var html = "";
    
    for(var i = 0; i < tags.length; i++) {
        if(tags[i].length > 0) {
            html += '<a onclick="removeFilter(\'' + tags[i] + '\')" href="#cloud' + TagsToPermalink(_tags, tags[i], true) + '" title="Remove this filter">' + tags[i] + '</a>';
            
            if(i < tags.length -1) {
                html += ', ';
            }
        }
    }
    
    html = trim(html);
    
    if(html.charAt(html.length-1) == ',') {
        html = html.substring(0,html.length-1);
    }
    
    return html;
}

function TagsToPermalink(currentTags, tag, remove) {
    if(remove == undefined)
        remove = false;

    if(remove) {
        if(currentTags.indexOf(tag) > -1) {
            currentTags = currentTags.replace(", " + tag, "");
            currentTags = currentTags.replace(tag + ", ", "");
            currentTags = currentTags.replace(tag, "");
        }
    } else {
        if(currentTags.indexOf(tag) < 0) {
            currentTags = currentTags + ", " + tag;
        }
    }

    var tags = currentTags.split(",");
    
    var html = "";
    
    for(var i = 0; i < tags.length; i++) {
        if(tags[i].length > 0) {
            html += ':' + trim(tags[i]);
        }
    }
    
    html = trim(html);
    
    if(html.charAt(html.length-1) == ':') {
        html = html.substring(0,html.length-1);
    }
    
    return html;
    
    
}

function removeFilter(tag) {
    if(_tags == tag || _tags == tag + ",") {
        GetImageCloud();
    } else {
        _tags = _tags.replace(tag + ",", "").replace(tag, "");
        LimitImages();
    }
}

function LimitImages(tag) {
    if(tag != undefined) {
        if(_tags.length > 0) {
            if(_tags.indexOf(tag) < 0) {
                _tags += ", " + tag;
            }
        } else {
            _tags = tag;
        }
    }

    showUpdate("Please wait, fetching images...");

    jQuery.post("/Home/LimitImages", { limit: _tags }, function (data) {
        OnLimitImages(data);
        googleTracker({ category: "Image cloud", action: "Limit images", label: _tags });
    }, "json");
}

function LimitImagesOnLoad(tags) {
    var regex = /:/g;
    
    tags = tags.replace(regex,",");    
    _tags = tags;

    showUpdate("Please wait, fetching images...");

    jQuery.post("/Home/LimitImages", { limit: _tags }, function (data) {
        OnLimitImages(data);
    }, "json");
}

var _thumbnails = true;

function ShowThumbnails() {
    var images = document.body.getElementsByTagName("img");
    
    for(var i = 0; i < images.length; i++) {
        var image = images[i];
        
        if(image != null && image.className.indexOf("thumbnail") > -1) {
            var url = image.getAttribute("url");
            
            if(image.src != url) {
                image.src = image.getAttribute("url");
            }
        
            if(image.className.indexOf("hide") > -1) {
                ShowObject(image);
                _thumbnails = true;
            } else {
                HideObject(image);
                _thumbnails = false;
            }
        }
    }
}

function limitTextSize(source, maxLength, trailingDots) {
    if (source.length > maxLength) {
        if (trailingDots) maxLength -= 3;

        source = source.substring(0, maxLength);

        if (trailingDots) source += "...";
    }

    return source;
}

function OnLimitImages(results) {
    var html = '<h2>Images: ' + results.length + ' found</h2>';
    html += '<p class="go-right"><a onclick="ShowThumbnails()" href="' + location.hash + '">Show/hide thumbnails</a></p>';
    html += '<p class="tags go-left">Filtering by: ' + GetTagFilters() + '</p>';
    html += '<div class="images clear">'

    for(var i = 0; i < results.length; i++) {
        var url = escape(results[i].Url);
        
        var index = url.lastIndexOf("/");
        var path = "";
        var file = "";
        var title = limitTextSize(results[i].Name, 25, true);

        if(index > 1) {
            path = url.substring(0, index+1);
            file = url.substring(index+1, url.length);
        }
        
        html += '<div class="image ' + (i%4 == 0 ? "clear" : "") + '">';
        html += '<a rel="prettyPhoto[gallery]" href="' + path + 'big_' + file + '" title="' + results[i].Name + '" id="image_link_' + i + '">';
        html += '<h4><span class="no">' + (i + 1) + '.</span> ' + title + '</h4>';

        html += '<img class="thumbnail ' + (!_thumbnails ? 'hide' : '') + '" url="' + path + 'thumbnail_' + file + '" src="' + path + 'thumbnail_' + file + '"/>';
        html += '</a>';
        
        html += '<p class="tags">Tags: ';
        
        for(var j = 0; j < results[i].Tags.length; j++) {
            html += '<a onclick="LimitImages(\'' + results[i].Tags[j] + '\')" href="#cloud' + TagsToPermalink(_tags, results[i].Tags[j]) + '" title="Search for images also tagged with: ' + results[i].Tags[j] + '">' + results[i].Tags[j] + '</a>';
            
            if(j < results[i].Tags.length-1) {
                html += ' | ';
            }
        }
        
        html += '</p>';
        html += '</div>';
    }
    html += '</div>';
    html += '<p class="clear"><a onclick="GetImageCloud()" href="#cloud">Go back to cloud</a></p>';
    
    stopUpdateWindow();
    ReplaceContent("body_container", html);

    InitPrettyPhoto("#body_container .images a[rel^='prettyPhoto']");
}

function InitPrettyPhoto(selector) {
    $(".pp_pic_holder").remove();
    $(".pp_overlay").remove();
    $(".ppt").remove();

    $(selector).prettyPhoto({ overlay_gallery: false });
}

function ChangeMetaTags(title, description, url) {
    var metaTags = document.getElementsByTagName("meta");
    
    var imageTags = document.getElementsByTagName("link");
    
    document.title = title;
    
    for(var i = 0; i < metaTags.length; i++) {
        var meta = metaTags[i];
        
        if(meta.getAttribute("name") == "title") {
            meta.setAttribute("content", title);
        }
        
        if(meta.getAttribute("name") == "description") {
            meta.setAttribute("content", description);
        }
    }
    
    for(var j = 0; j < imageTags.length; j++) {
        var image = imageTags[j];
        
        if(image.getAttribute("rel") == "image_src") {
            image.setAttribute("href", url);
        }
    }
}

function CreateImageXml() {
    showUpdate("Generating XML...");

    jQuery.post("/Home/CreateImageXml", null, function () {
        stopUpdateWindow();
        Message("Success", "XML created.");
    });
}

function EditGallery(name) {
    jQuery.post("/Home/GetGallery", {url: name}, function (results) {
        if(results != null) {
            var html = '<h2>Update gallery</h2>';
        
            html += '<table cellspacing="0" cellpadding="3" id="full-gallery">';
            html += '<tr><td></td><td>';
            html += '<div>';
            html += '<label for="gallery_title">Title: </label>';
            html += '<input id="gallery_title" value="' + results.Name + '"/>';
            html += '</div>';
            html += '<td>(<a href="javascript:DeleteNode(\'full-gallery\', \'gallery\',\'' + results.Url + '\')">Delete</a>)</td>';
            html += '</td></tr>';
            html += '<tr><td colspan="4"><h4>Images</h4></td></tr>';
        
            for(var i = 0; i < results.Images.length; i++) {
                html += '<tr id="gallery_node_' + i + '">';
                html += '<td><input id="image_' + i + '" value="' + results.Images[i].Url + '" type="hidden"/>';
                html += '<a href="/content/images/gallery/' + results.Url + '/small_' + results.Images[i].Url + '" target="_blank"><img align="left" src="/content/images/gallery/' + results.Url + '/thumbnail_' + results.Images[i].Url + '" border="0"/></a></td>';
                html += '<td>';
                html += '<div>';
                html += '<label for="image_' + i + '_name">Name: </label><input id="image_' + i + '_name" value="' + results.Images[i].Name + '"/>';
                html += '</div>';
                html += '<div>';
                html += '<label for="image_' + i + '_tags">Tags: </label><input id="image_' + i + '_tags" value="' + results.Images[i].Tags.join(', ') + '"/>';
                html += '</div>';
                html += '<div>';
                html += '(<a href="javascript:DeleteNode(\'gallery_node_' + i + '\', \'image\',\'' + results.Url + '\',\'' + results.Images[i].Url + '\')">Delete</a>)';            
                html += '</div>';
                html += '</td>';
                html += '<td>';
                html += '</td>';
                html += '</tr>';
            }
        
            html += '<tr><td></td><td colspan="3">';
            html += '<div><button onclick="UpdateGallery(\'' + results.Url + '\',\'' + results.Images.length + '\')">OK</button><button onclick="goBack()">Cancel</button></div>';
            html += '</td></tr>';
            html += '</table>';
        
            ReplaceContent("body_container",html);        
        }
    }, "json");
}

function EditGalleries() {
    jQuery.post("/Home/GetGalleries", null, function (results) {
        var html = '<h2>Galleries</h2><ul>';

        for (var i = 0; i < results.length; i++) {
            html += '<li><a href="javascript:EditGallery(\'' + results[i].Url + '\')">' + results[i].Name + '</a></li>';
        }

        html += '</ul>';

        ReplaceContent("body_container", html);
    }, "json");
}

function UpdateGallery(galleryname, count) {
    var title = document.getElementById("gallery_title").value;
    var images = new Array();
    
    for(var i = 0; i < count; i++) {
        var check = document.getElementById("image_" + i);
        
        if(check != null) {    
            var url = document.getElementById("image_" + i).value;
            var name = document.getElementById("image_" + i + "_name").value;
            var tags = document.getElementById("image_" + i + "_tags").value;

            images.push({ "Url": url, "Name": name, "JsonTags": tags });
        }
    }

    //Setup json serializer
    JSONstring.compactOutput = false;
    JSONstring.includeProtos = false;
    JSONstring.includeFunctions = false;
    JSONstring.detectCirculars = false;
    JSONstring.restoreCirculars = false;

    var jsonImages = JSONstring.make(images);

    jQuery.post("/Home/UpdateGallery", { galleryName: galleryname, galleryTitle: title, images: jsonImages }, function () {
        Message("Success", "The gallery was updated.");
    });
}

function DeleteNode(id, type, value, optional) {
    if(optional == undefined)
        optional = "";
        
    var obj = document.getElementById(id);
    
    if(obj != null) {
        obj.parentNode.removeChild(obj);
    }

    jQuery.post("/Home/DeleteNode", { nodeName: type, nodeValue: value, optionalValue: optional }, function () {
        Message("Success", "The gallery was updated.");
    });
}

function GetGalleries() {
    showUpdate("Please wait, fetching galleries...");

    jQuery.post("/Home/GetGalleries", null, function (results) {
        stopUpdateWindow();
        var html = '<h2>Image galleries</h2>';
        html += '<p class="tooltip">Browse for the image you need</p>';
        html += '<ul class="image_gallery">';

        for (var i = 0; i < results.length; i++) {
            if (results[i].Name.toLowerCase() != 'miscellaneous') {
                html += '<li class="gallery">';
                html += '<h4>' + results[i].Name + ' <span>(' + results[i].Images.length + ' images)</span></h4>';

                for (var j = 0; j < results[i].Images.length; j++) {

                    var img = results[i].Images[j];
                    var url = escape(img.Url);

                    var path = "/content/images/gallery/" + results[i].Url + "/big_" + url;
                    var thumb = "/content/images/gallery/" + results[i].Url + "/thumbnail_" + url;

                    if (j == 0) {
                        html += '<a rel="prettyPhoto[gallery-' + i + ']" href="' + path + '" title="' + img.Name + '" id="image_link_' + i + '">';
                        html += '<img src="' + thumb + '"/>';
                        html += '</a>';
                    } else {
                        html += '<a class="hide" rel="prettyPhoto[gallery-' + i + ']" href="' + path + '" title="' + img.Name + '" id="image_link_' + i + '">' + img.Name + '</a>';
                    }
                }
                html += '</li>';
            }
        }

        html += '</ul><div class="clear"></div>';

        ReplaceContent("body_container", html, false);

        $("ul.image_gallery a[rel^='prettyPhoto']").prettyPhoto({ overlay_gallery: false, slideshow: 15000, autoplay_slideshow: true });
    }, "json");
}

function UploadImages() {
    jQuery.post("/Home/GetGalleries", null, function (results) {
        OnUploadImages(results);
    }, "json");
}

function OnUploadImages(results) {
    var html = '<h2>Upload images to:</h2>';
    html += '<div>';
    html += '<label for="upload_gallery">Gallery: </label>';
    html += '<select id="upload_gallery">';
    html += '<option value="">Select:</option>';
    
    for(var i = 0; i < results.length; i++) {
        html += '<option value="' + results[i].Url + '">' + results[i].Name + '</option>';
    }
    
    html += '</select>';
    html += '</div>';
    html += '<div><label for="upload_new_gallery">Or create a new one:</label>';
    html += '<input id="upload_new_gallery" maxlength="15" size="25"/></div>';
    html += '<div>';
    html += '<button onclick="SelectUploadGallery()">OK</button><button onclick="goBack()">Cancel</button>';
    html += '</div>';
    
    ReplaceContent("body_container", html);
}

function SelectUploadGallery() {
    var new_gallery = document.getElementById("upload_new_gallery").value;
    var old_gallery = document.getElementById("upload_gallery").value;
    var _gallery = "";
    
    if(new_gallery.length > 0) {
        _gallery = new_gallery.toLowerCase();
    } else {
        _gallery = old_gallery;
    }

    document.location.href = "/Home/Upload/?gallery=" + _gallery;
}

function CreateThumbnails() {
    showUpdate("Creating thumbnails...");

    jQuery.post("/Home/CreateThumbnails", null, function () {
        Message("Success", "Thumbnails created.");
    });
}

/*** shared objects ***/

function addOption(obj, value, name, nameOfClass) {
    if(nameOfClass == undefined)
        nameOfClass = "";

    var optionObject = new Option(name, value)
    var optionRank = 0;
        
    if(obj.options == null)
        optionRank = 0;
    else {
        optionRank = obj.options.length;
    }
    
    optionObject.className = nameOfClass;
    
    obj.options[optionRank] = optionObject;
}

//Limit the number of characters in a text area 
function limitCharacters(obj,limit) {
    var text = obj.value;
    
    if(text.length > limit) {
        obj.value = text.substring(0,limit);
    }
}

//Trim leading and trailing spaces and empty lines
function trim(str) {
    var regex = /^[ \t\r\n]+|[ \t\r\n]+$/;

    return str.replace(regex, "");
}

//Strip HTML tags from a string
function stripHtml(str) {
    var regex = /<[^>]*>/g;

    return str.replace(regex, "");
}

var _zIndex = 500;

function CreateHoverWindow(name, text, nameOfClass) {
    var body = document.body;
    
    var windowCheck = document.getElementById("global_content_" + name);
    
    if(!windowCheck) {
        var hoverContainer = document.createElement("div");
        hoverContainer.setAttribute("id", "hover_" + name);
        hoverContainer.className = "global_hover_container";
        hoverContainer.style.zIndex = _zIndex++;
                
        var closeContainer = document.createElement("div");  
        
        var closeLink = document.createElement("a");
        closeLink.innerHTML = "<span>Close</span>";
        closeLink.className = "img_replace global_close_window";
        
        if(name == 'gallery') {
            closeLink.href = "javascript:CloseSlideShow();";
        } else {
            closeLink.href = "javascript:RemoveHoverWindow('" + name + "');";
        }
        
        closeLink.style.zIndex = _zIndex++;
        
        var popup = document.createElement("div");
        popup.className = "global_popup " + nameOfClass;
        popup.setAttribute("id", "rounded_" + name);
        
        closeContainer.appendChild(closeLink);
        popup.appendChild(closeContainer);
        
        var content = document.createElement("div");    
        content.className = "global_content";
        content.setAttribute("id", "global_content_" + name);
        content.innerHTML = text;
        
        popup.appendChild(content);             
        
        hoverContainer.appendChild(popup);
        body.insertBefore(hoverContainer, body.firstChild);
                
        //Automatically set focus to the first input
        var inputs = content.getElementsByTagName("input");

        if(inputs.length > 0) {
            for(var i = 0; i < inputs.length; i++) {
                if(inputs[i].getAttribute("type") == null || inputs[i].getAttribute("type") != "hidden") {
                    inputs[i].focus();
                    break;
                }
            }
        }            
        
        var background = "#ebf0f4";
        
        if(nameOfClass == "global_error")
            background = "#c90000";
        else if(nameOfClass == "global_message")
            background = "#72c604";
        else if(nameOfClass == "global_questions")
            background = "#ffffff";
        else if(nameOfClass == "global_confirmation")
            background = "#75c1e9";
        else if(nameOfClass == "global_object")
            background = "#193e57";
        
    } else {
        windowCheck.innerHTML = text;
    }
}

function RemoveHoverWindow(id) {
    var objWindow = document.getElementById("hover_" + id);
    
    if (objWindow != null) 
    {
        document.body.removeChild(objWindow);
    }
    
    //Get Image Cloud on close when people are coming directly to a gallery or photo
    if(_permalink) {
        _permalink = false;
        location.replace(location.pathname + "#cloud");
        GetImageCloud();
    }
}

//For web services
function OnError(error) {
    html = '<h2>Error</h2>';
    html += '<p>' + error.get_message() + '</p>';
    stopUpdateWindow();
    
    CreateHoverWindow('error', html, 'global_error');
}

//For other purposes
function Error(error) {
    html = '<h2>Error</h2>';
    html += '<p>' + error + '</p>';
    stopUpdateWindow();
    
    CreateHoverWindow('error', html, 'global_error');
}

function Message(title, text, fade) {
    if(fade == undefined)
        fade = true;
    
    html = '<h2>' + title + '</h2>';
    html += '<p>' + text + '</p>';
    
    CreateHoverWindow('message', html, 'global_message');
    stopUpdateWindow();
    
    if(fade) {
        setTimeout("fadeMessage()",2000);
    }
}

function fadeMessage() {
    var message = $('#rounded_message');

    message.fadeIn('slow', function () {
        RemoveHoverWindow("message");
    });
}

function fadeContainer(container, start, finish) {
    var fader = $("#" + container);

    if (start == 0) {
        fader.fadeIn('slow');
    } else if (start == 1) {
        fader.fadeOut('slow');
    }
}


/*** update ***/

var updateTimer;
var updateMinTime = 500;
var updateCanStop = false;
var updateFinished = false;

function showUpdate(text) {
    updateFinished = false;
    updateCanStop = false;

    var updateContainer = document.getElementById("update_container");
    
    if(!updateContainer) {
        $(document.body).append("<div id='update_container'><div id='update_animation'></div></div>");
    }

    $("#update_animation").html(text);
    $("#update_container").show();
    
    updateTimer = setTimeout("stopUpdateTimer()",updateMinTime);
}

function stopUpdateTimer() {
    updateCanStop = true;
    clearTimeout(updateTimer);
    
    if(updateFinished)
    {
        stopUpdateWindow();
    }
}

function stopUpdateWindow() {
    updateFinished = true;
    
    if(updateCanStop) {
        fadeContainer('update_container', 1, 0);
    }
}

var _historyLink = location.hash;
var _historyTimer = null;

function ObserveHistory() {
    var link = location.hash;
    
    if(_historyLink != link) {
        //goBack();
    }
    
    _historyLink = link;
}

function CheckPermaLink() {
    var hash = location.hash;
    
    if(hash.indexOf("#gallery:") > -1 || hash.indexOf("#img:") > -1) {
        _permalink = true;
    }
}

function AjaxHistory() {
    var page = location.href.toLowerCase();
    var hash = location.hash.toLowerCase();

    if (hash.length > 0) {
        if (hash.indexOf("#cloud") > -1) {
            if (hash.indexOf("#cloud:") > -1) {
                var tags = hash.replace("#cloud:", "");

                LimitImagesOnLoad(tags);
            } else {
                GetImageCloud();
            }
        }
        else if (hash.indexOf("#gallery") > -1) {
            if (hash.indexOf("#gallery:") > -1) {

                var gallery = hash.replace("#gallery:", "");

                GetGallery(gallery);
            }
        }
        else if (hash.indexOf("#img") > -1) {
            if (hash.indexOf("#img:") > -1) {
                var photo = hash.replace("#img:", "");

                OpenImage(photo);
            } else {
                GetImageCloud();
            }
        }
        else {
            GetImageCloud();
        }
    } else {
        if (page.indexOf("/home/galleries") > -1) {
            GetGalleries();
        } else {
            GetImageCloud();
        }
    }
}

function fbs_click(u) { t = document.title; window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436'); return false; }

//Google Page Tracker
function googleTracker(opts) {
    if (opts == undefined) opts = { category: null, action: null, label: null, value: null };

    if (_gaq == undefined) {
    } else if (_gaq != null) {
        if (opts.value != null) {
            _gaq.push(['_trackEvent', opts.category, opts.action, opts.label, opts.value]);
        } else if (opts.label != null) {
            _gaq.push(['_trackEvent', opts.category, opts.action, opts.label]);
        } else {
            _gaq.push(['_trackEvent', opts.category, opts.action]);
        }
    }
}
