﻿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() {
    tinna.Core.Soap.FrontEnd.Menu(OnMenu, OnError);
}

function OnMenu(results) {
    if(results) {
        var html = '<ul>';
        html += '<li><a href="javascript:GetNewsList(15935, 0, 3)">Blog</a>';
        html += '<ul><li><a href="javascript:Blog()">New blog entry</a></li></ul>';
        html += '</li>';
        html += '<li><a href="javascript:GetImageCloud()">Image gallery</a>';
        html += '<ul>';
        html += '<li><a href="javascript:UploadImages()">Upload images</a></li>';
        html += '<li><a href="javascript:CreateImageXml()">Update gallery XML</a></li>';
        html += '<li><a href="javascript:EditGalleries()">Update galleries</a></li>';
        html += '<li><a href="javascript:CreateThumbnails()">Create thumbnails</a></li>';
        html += '</ul>';
        html += '</li>';
        html += '<li class="logout"><a href="javascript:Logout()">Logout</a></li>';
        html += '</ul>';
        ReplaceContent("menu_container", html);
    } else {
        var html = '<ul>';
        html += '<li><a onclick="GetBlog()" href="#blog">Blog</a></li>';
        html += '<li><a onclick="GetImageCloud()" href="#cloud">Image gallery</a></li>';
        html += '</ul>';
        ReplaceContent("menu_container", html);
    }
}

function Login() {
    var user = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    
    tinna.Core.Soap.FrontEnd.Login(user, password, OnLogin, OnError);
}

function OnLogin() {
    document.location.href = "/tinna/default.aspx";
}

function Logout() {
    tinna.Core.Soap.FrontEnd.Logout(OnLogin, OnError);
}

function GetBlog(page) {
    if(page == undefined)
        page = 0;
        
    GetNewsList(15935, page, 3);
}

function GetNewsList(catId, page, itemsPerPage) {
    showUpdate("Please wait, fetching articles...");
    tinna.Core.Soap.FrontEnd.GetNewsList(catId, page, itemsPerPage, false, OnNewsList, OnError);
}

function OnNewsList(results) {
    stopUpdateWindow();
    ReplaceContent("body_container", results);
    
    GetComments();
}

function ReadArticle(articleId) {
    showUpdate("Please wait, fetching article...");
    tinna.Core.Soap.FrontEnd.GetNewsItem(articleId, OnNewsList, OnError);
}

function EditArticle(articleId) {
    tinna.Core.Soap.FrontEnd.GetNewsForEdit(articleId, OnEditArticle, OnError);
}

function OnEditArticle(results) {
    ReplaceContent("body_container", results);
}

function UpdateArticle(newsId) {
    var headline = document.getElementById("blog_title").value;
    var htmltext = document.getElementById("blog_content").value;
    var previewtext = document.getElementById("blog_summary").value;
    var catId = document.getElementById("blog_category").value;
    var online = document.getElementById("blog_online").value;
    var offline = document.getElementById("blog_offline").value;
    var eventdate = document.getElementById("blog_event").value;
    var author = document.getElementById("blog_author").value;
    var position = document.getElementById("blog_posvalue").value;
    var related = document.getElementById("blog_related").value;

    showUpdate("Please wait, posting...");
    tinna.Core.Soap.FrontEnd.EditBlog(headline, htmltext, previewtext, newsId, catId, online, offline, eventdate, author, position, related, OnUpdateBlog, OnError);
}

function OnUpdateBlog() {
    document.location.href = "/tinna/default.aspx";
}

function GetComments() {
    var blogId = document.getElementById("blog_id");
    
    if(blogId) {
        var newsId = blogId.getAttribute("guid");        
        tinna.Core.Soap.FrontEnd.GetThreads(newsId, OnComments, OnError);
    }
}

function OnComments(results) {
    if(results == "") {
        results += '<div class="hide" id="comment_container">';
        results += '<div>';
        results += '<label for="comment_author">Name: *</label>';
        results += '<input id="comment_author" maxlength="30" size="30" class="validate"/>';
        results += '</div>';
        results += '<div>';
        results += '<label for="comment_email">E-mail: *</label>';
        results += '<input id="comment_email" maxlength="30" size="30" class="validate email"/>';
        results += '</div>';
        results += '<div>';
        results += '<label for="comment_content">Message: *</label>';
        results += '<textarea id="comment_content" rows="3" cols="30" class="validate"></textarea>';
        results += '</div>';
        results += '<div>';
        results += '    <input type="hidden" id="captchahash" value=""/>';
        results += '    <img id="captchaimg" src="upload/files/templates/js/blank.gif" onclick="return LoadCaptcha();" alt="Image verification" title="If you are unable to see the image, click here to regenerate" />';
        results += '</div>';
        results += '<div>';
        results += '    <label for="captcha_input" title="Type in the letters you see in the above image">Verification: *</label>';
        results += '    <input type="text" id="captcha_input" size="20" class="validate" maxlength="20" />';
        results += '</div>';
        results += '<div>';
        results += '<button onclick="PostComment(0)">OK</button><button onclick="HideComments()">Cancel</button>';
        results += '</div>';
        results += '</div>';
    }
    
    stopUpdateWindow();
    ShowObject("comment_link");
    ReplaceContent("article_comments", results, false);
    LoadCaptcha();
}

function HideComments() {
    HideObject("comment_container");
}

function LoadCaptcha() {
    tinna.Core.Soap.FrontEnd.GetCaptcha(OnSuccessCaptcha);
}

function OnSuccessCaptcha(results) {
    var s1 = results[0];
    var s2 = results[1];
    
    var captcha = document.getElementById("captchaimg");
    
    if(captcha) {
        captcha.src = 'upload/files/templates/js/CaptchaImage.aspx?text=' + s1;
        document.getElementById("captchahash").value = s2;
    }
}

function Blog() {
    var html = '<h1>Blog</h1><div>';
    html += '    <label for="blog_category">Category: *</label>';
    html += '    <select id="blog_category"></select>';
    html += '</div>';
    html += '<div>';
    html += '    <label for="blog_title">Title: *</label>';
    html += '    <input type="text" id="blog_title" maxlength="50" size="40" class="validate"/>';
    html += '</div>';
    html += '<div>';
    html += '    <label for="blog_author">Author: *</label>';
    html += '    <input type="text" id="blog_author" maxlength="20" size="20" class="validate" value="Tinna Karen" />';
    html += '</div>';
    html += '<div>';
    html += '   <label for="blog_summary">Summary: *</label>';
    html += '    <textarea id="blog_summary" rows="5" cols="30" class="validate"></textarea>';
    html += '</div>';
    html += '<div>';
    html += '    <label for="blog_content">Content: *</label>';
    html += '    <textarea id="blog_content" rows="15" cols="30" class="validate"></textarea>';
    html += '</div>';
    html += '<div>';
    html += '    <button onclick="PostBlog()">OK</button><button onclick="goBack()">Cancel</button>';
    html += '</div>';

    ReplaceContent("body_container", html);

    GetCategories();
}

function PostBlog() {
    var category = document.getElementById("blog_category").value;
    var title = document.getElementById("blog_title").value;
    var author = document.getElementById("blog_author").value;
    var summary = document.getElementById("blog_summary").value;
    var content = document.getElementById("blog_content").value;
    
    if(validateForm("body_container","is missing")) {
        showUpdate("Please wait, posting...");
        tinna.Core.Soap.FrontEnd.Blog(title, author, summary, content, category, OnBlog, OnError);
    }
}

function OnBlog() {
    document.location.href = "/tinna/default.aspx";
}

function Comment() {
    var blogId = document.getElementById("blog_id");
    
    if(blogId) {
        var newsId = blogId.getAttribute("guid");
        
        if(newsId != null && newsId.length > 0) {
            //allow comments
            ShowObject("comment_container");
        }
    }
}

function Reply(id, admin, email) {
    if(admin == undefined) {
        admin = false;
    }
    
    if(email == undefined) {
        email = "";
    }
    
    document.getElementById("comment_reply_id").value = id;
    document.getElementById("comment_reply").value = "true"; 
        
    if(admin) {
        document.getElementById("comment_reply_email").value = email; 
    }
    
    Comment();    
}

function PostComment(id) {
    var blogId = document.getElementById("blog_id");
       
    if(blogId) {
        var newsId = blogId.getAttribute("guid");
        
        if(newsId != null && newsId.length > 0) {
            var author = document.getElementById("comment_author").value;
            var reply = "false";
            var replyid = "";
            var replyemail = "";

            var isReply = document.getElementById("comment_reply");
            
            if(isReply) {
                reply = isReply.value;
                replyid = document.getElementById("comment_reply_id").value;
                replyEmailContainer = document.getElementById("comment_reply_email");

                if(replyEmailContainer) replyemail = replyEmailContainer.value;
            }

            var email = document.getElementById("comment_email").value;
            var content = document.getElementById("comment_content").value;
            var hash = document.getElementById("captchahash").value;
            var captcha = document.getElementById("captcha_input").value;
            
            if(validateForm("comment_container","is missing","","is not valid")) {
                showUpdate("Please wait, posting...");
                tinna.Core.Soap.FrontEnd.PostComment(newsId, blogId.innerHTML, author, email, content, id, hash, captcha, reply, replyid, replyemail, OnComment, OnError);   
            }
        }
    }
}

function OnComment(results) {
    var html = "<h4>Thanks!</h4><p>The comment has been sent to me for approval.</p>";    
    stopUpdateWindow();
    
    ReplaceContent("comment_container", html, false);
    HideObject("comment_link");
}

function UpdateComment(id, approve) {
    var blogId = document.getElementById("blog_id");
    
    if(blogId) {
        var newsId = blogId.getAttribute("guid");
        
        if(newsId != null && newsId.length > 0) {
        
            if(approve) {
                var author = document.getElementById("blog_approve_author_" + id).innerHTML;
                var content = document.getElementById("blog_approve_content_" + id).innerHTML;
                var email = document.getElementById("blog_approve_email_" + id).innerHTML;
                var subject = document.getElementById("blog_approve_subject_" + id).innerHTML;
                
                if(author.length > 0 && content.length > 0) {
                    showUpdate("Please wait, updating...");
                    tinna.Core.Soap.FrontEnd.UpdateComment(newsId, subject, content, id, author, email, approve, OnCommentUpdated, OnError);   
                }
            } else {
                 showUpdate("Please wait, updating...");
                    tinna.Core.Soap.FrontEnd.UpdateComment(newsId, "", "", id, "", "", approve, OnCommentUpdated, OnError); 
            }
        }
    }
}

function OnCommentUpdated(results) {
    GetComments();
}

function DeletePost(postId) {
}

function GetCategories() {
    tinna.Core.Soap.FrontEnd.GetCategories(OnCategories, OnError);
}

function OnCategories(results) {
    var categoryObject = document.getElementById("blog_category");
    
    for(var i = 0; i < results.length; i++) {
        addOption(categoryObject, results[i].Path, results[i].Name);
    }
}

/** gallery **/
var _tags = "";

function GetImageCloud() {
    showUpdate("Please wait, fetching gallery...");
    _tags = "";
    tinna.Core.Soap.FrontEnd.GetImageCloud(OnImageCloud, OnError);
}

function OnImageCloud(results) {
    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 < results.length; i++) {
        html += '<li style="font-size:' + (results[i].Size) + '%"><a onclick="LimitImages(\'' + results[i].Name + '\')" href="#cloud:' + results[i].Name + '" title="Search for images tagged with: ' + results[i].Name + '">' + results[i].Name + '</a></li>';
    }
    
    html += '<div class="clear"></div></ul><div id="gallery_container"></div>';
    stopUpdateWindow();
    ReplaceContent("body_container", html);
    
    GetGalleries();
}

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...");
    tinna.Core.Soap.FrontEnd.LimitImages(_tags, OnLimitImages, OnError);
}

function LimitImagesOnLoad(tags) {
    var regex = /:/g;
    
    tags = tags.replace(regex,",");    
    _tags = tags;
    
    showUpdate("Please wait, fetching images...");
    tinna.Core.Soap.FrontEnd.LimitImages(_tags, OnLimitImages, OnError);
}

var _thumbnails = false;

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 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>';
    
    for(var i = 0; i < results.length; i++) {
        var url = escape(results[i].Url);
        
        var index = url.lastIndexOf("/");
        var path = "";
        var file = "";
        
        if(index > 1) {
            path = url.substring(0, index+1);
            file = url.substring(index+1, url.length);
        }
        
        html += '<div class="image clear">';
        html += '<h4>' + (i+1) + '. <a onclick="OpenImage(\'' + url + '\',' + i + ')" href="#img:' + url + '" title="Open the image in a new layer" id="image_link_' + i +'">' + results[i].Name + '</a></h4>';
        
        html += '<a onclick="OpenImage(\'' + url + '\',' + i + ')" href="#img:' + url + '" title="Open the image in a new layer" id="image_link_' + i +'">';
        
        if(_thumbnails) {
            html += '<img class="thumbnail" alt="' + results[i].Name + '" url="' + path + 'thumbnail_' + file + '" src="' + path + 'thumbnail_' + file + '"/>';
        } else {
            html += '<img class="thumbnail hide" alt="' + results[i].Name + '" url="' + path + 'thumbnail_' + file + '" src=""/>';
        }
        
        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 += '<p><a onclick="GetImageCloud()" href="#cloud">Go back to cloud</a></p>';
    
    stopUpdateWindow();
    ReplaceContent("body_container", html);
}

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 OpenImage(url, i) {
    var name = "";
    
    if(i == undefined) {
        name = "";
    } 
    else {
        name = document.getElementById("image_link_" + i).innerHTML;
    }

    var html = '<h2>' + name + '</h2>';
       
    var index = url.lastIndexOf("/");
    
    if(index > 1) {
        var path = url.substring(0, index+1);
        var file = url.substring(index+1, url.length);
        
        ChangeMetaTags(name, "Photo from tinna.net", "http://tinna.net/tinna/" + path + 'small_' + file);
        
        var facebookImg = path + 'small_' + file;
        
        html += '<div id="gallery_image"><img src="' + path + 'small_' + file + '" id="image_fader"/>';
        html += '<p><small>&reg; Tinna Karen &copy; Copyright 2003-2008</small><br/><br/><a href="' + path + 'big_' + file + '" target="_blank">Download a full size version</a>';
               
        if(name.length > 0) {
            html += ' | <a href="#img:' + url + '" onclick="return fbs_click(\'http://tinna.net/?type=img&url=' + facebookImg + '&title=' + encodeURIComponent(escape(name)) + '#img:' + url  + '\')" target="_blank">Share on Facebook</a>';
        }
        
        html += '</p></div>';
        
        CreateHoverWindow("gallery", html, "global_gallery");
        
        fadeContainer("image_fader", 0, 1);
    }
}

function CreateImageXml() {
    tinna.Core.Soap.FrontEnd.CreateImageXml(OnXmlCreated, OnError);
}

function OnXmlCreated() {
    Message("Success", "XML created.");
}

function EditGallery(name) {
    tinna.Core.Soap.FrontEnd.GetGallery(name, OnEditGallery, OnError);
}

function OnEditGallery(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="/tinna/upload/images/gallery/' + results.Url + '/small_' + results.Images[i].Url + '" target="_blank"><img align="left" src="/tinna/upload/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);        
    }
}

function EditGalleries() {
    tinna.Core.Soap.FrontEnd.GetGalleries(OnEditGalleries, OnError);
}

function OnEditGalleries(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);
}

function UpdateGallery(galleryname, count) {
    var title = document.getElementById("gallery_title").value;
    var imageUrlArr = new Array();
    var imageNameArr = new Array();
    var imageTagsArr = 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;
            
            imageUrlArr[i] = url;
            imageNameArr[i] = name;
            imageTagsArr[i] = tags;
        }
    }
    
    tinna.Core.Soap.FrontEnd.UpdateGallery(galleryname, title, imageUrlArr, imageNameArr, imageTagsArr, OnGalleryUpdated, OnError);
}

function DeleteNode(id, type, value, optional) {
    if(optional == undefined)
        optional = "";
        
    var obj = document.getElementById(id);
    
    if(obj != null) {
        obj.parentNode.removeChild(obj);
    }
    
    tinna.Core.Soap.FrontEnd.DeleteNode(type, value, optional, OnGalleryUpdated, OnError);
}

function OnGalleryUpdated() {
    Message("Success", "The gallery was updated.");
}

function GetGalleries() {
    tinna.Core.Soap.FrontEnd.GetGalleries(OnGetGalleries, OnError);
}

function OnGetGalleries(results) {
    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++) {
        html += '<li class="gallery"><a onclick="GetGallery(\'' + results[i].Url + '\')" href="#gallery:' + results[i].Url + '">' + results[i].Name + '</a></li>';
    }
    
    html += '<div class="clear"></div></ul>';
    
    ReplaceContent("gallery_container", html, false);
}

function GetGallery(name) {
    tinna.Core.Soap.FrontEnd.GetGallery(name, OnGetGallery, OnError);
}

var _imgArray;
var _imgUrl = "";
var _imgPath = "";
var _imgTitle = "";
var _current = 0;

function prevImg() {
    fadeContainer("image_fader", 1, 0);

    if(_imgArray != null && _imgArray.length > 0) {
        _current = _current-1;
        
        if(_current < 0)
            _current = _imgArray.length-1;
            
        UpdateImg();
    }
}

function UpdateImg() {
    var img = document.getElementById("gallery_image");
        
    if(img) {
        var html = '<h2>' + _imgArray[_current].Name + ' (' + (_current+1) + '/' + _imgArray.length + ')</h2>';
        html += '<img src="' + _imgPath + '/' + _imgUrl + '/small_' + _imgArray[_current].Url + '" id="image_fader"/>';
        
        ReplaceContent("gallery_image", html, false);
        fadeContainer("image_fader", 0, 1);
    }
}

function nextImg() {
    fadeContainer("image_fader", 1, 0);
    
    if(_imgArray != null && _imgArray.length > 0) {
        _current = _current+1;
        
        if(_current > _imgArray.length-1)
            _current = 0;
            
        UpdateImg();
    }
}

var _slideShowTimer = "";
var _countDownTimer = "";
var _imageCountDownStart = 7;
var _imageCountDown = _imageCountDownStart;

function OnGetGallery(results) {
    if(results != null) {        
        
        if(results.Images.length > 0) {
            _imgArray = results.Images;
            _imgUrl = results.Url;
            _imgPath = results.Path;
            
            var html = '<div id="gallery_image"><h2>' + results.Images[0].Name + ' (1/' + _imgArray.length + ')</h2>';
            html += '<img src="' + results.Path + '/' + results.Url + '/small_' + results.Images[0].Url + '" id="image_fader"/></div>';
            html += '<p><small>&reg; Tinna Karen &copy; Copyright 2003-2009</small></p>';
            
            if(_imgArray.length > 1) {
                html += '<p><span onclick="prevImg()" title="Previous image"><<</span> | <span onclick="StartSlideShow()" id="slideshow_on" title="View as a slideshow">Play</span> <span onclick="StopSlideShow()" id="slideshow_off" class="hide" title="Stop slideshow">Stop</span> | <span onclick="nextImg()" title="Next image">>></span></p>';
                html += '<p id="slideshow_counter" class="hide">Next photo in <span id="slideshow_count">' + _imageCountDownStart + '</span> seconds</p>';
            }
        }
        
        CreateHoverWindow("gallery", html, "global_gallery");
        fadeContainer("image_fader", 0, 1);
    }
}

function StartSlideShow() {
    HideObject("slideshow_on");
    ShowObject("slideshow_counter");
    ShowObject("slideshow_off");
    
    _slideShowTimer = setTimeout("SlideShow()",500);
}

function CloseSlideShow() {
    StopSlideShow();
    
    RemoveHoverWindow('gallery');
}

function ImageCountDown() {
    var container = document.getElementById("slideshow_count");
    
    _imageCountDown = (_imageCountDown-1);
    container.innerHTML = _imageCountDown;
}

function StopSlideShow() {
    HideObject("slideshow_off");
    HideObject("slideshow_counter");
    ShowObject("slideshow_on");

    clearTimeout(_slideShowTimer);
}

function SlideShow() {
    if(_imageCountDown == 0) {    
        _imageCountDown = _imageCountDownStart;        
        nextImg();
    }
    
    ImageCountDown();       
    _slideShowTimer = setTimeout("SlideShow()",1000);
}

function UploadImages() {
    tinna.Core.Soap.FrontEnd.GetGalleries(OnUploadImages, OnError);
}

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;
    } else {
        _gallery = old_gallery;
    }
    
    //Upload parameters
    var _hostUrl = document.location.protocol + '//' + document.location.host
    var _archiveUrl = _javaUploader;
    var _servletUrl = _hostUrl + _javaUploader + 'Upload.aspx';
    var _msgUrl = _hostUrl + _javaUploader + 'blank.html';
    var _appletHeight = '104';
    var _appletWidth = '134';    
            
    var html = new Array();
    html[html.length] = '<div id="drop_box_container">';
    html[html.length] = '<h3>Drop box</h3>';
    html[html.length] = '<div class="drop_box" title="You can drag and drop files here">';

    var _info = navigator.userAgent;
    var ie = (_info.indexOf("MSIE") > 0);
    var win = (_info.indexOf("Win") > 0);

    if(win)
    {
        if(ie)
        {
             html[html.length] = '<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"';
             html[html.length] = '      width="' + _appletWidth + '" height="' + _appletHeight + '" id="rup"';
             html[html.length] = '      codebase="http://java.sun.com/update/1.5.0/jinstall-1_5-windows-i586.cab#version=1,4,1">';
        }
        else
        {
            html[html.length] = '<object type="application/x-java-applet;version=1.4.1"';
            html[html.length] = 'width="' + _appletWidth + '" height="' + _appletHeight + '" id="rup">';
        }
        html[html.length] = '<param name="archive" value="' + _archiveUrl + 'dndplus.jar">';
        html[html.length] = '<param name="code" value="com.radinks.dnd.DNDAppletPlus">';
        html[html.length] = '<param name="name" value="Drop Box">';
        html[html.length] = '<param name="MAYSCRIPT" value="yes">';
        
    }
    else
    {
        /* mac and linux */
        html[html.length] = '<applet ';
        html[html.length] = '         archive  = "' + _archiveUrl + 'dndplus.jar"';
        html[html.length] = '         code     = "com.radinks.dnd.DNDAppletPlus"';
        html[html.length] = '         name     = "Drop Box"';
        html[html.length] = '         hspace   = "0"';
        html[html.length] = '         vspace   = "0" MAYSCRIPT="yes"';
        html[html.length] = '         width = "' + _appletWidth + '"';
        html[html.length] = '         height = "' + _appletHeight + '"';
        html[html.length] = '         align    = "middle" id="rup">';
    }

    /******    BEGIN APPLET CONFIGURATION PARAMETERS   ******/
	
	var servlet = _servletUrl;
	
	if(_gallery.length > 0) {
	    servlet += '?gallery=' + _gallery;
	}
	
	html[html.length] = '<param name="max_upload" value="200000">';
    html[html.length] = '<param name="message" value="' + _msgUrl + '">';
    html[html.length] = '<param name="url" value="' + servlet + '">';    
    html[html.length] = '<param name="jsnotify" value="yes">';
        
    /******    END APPLET CONFIGURATION PARAMETERS     ******/
    if(win)
    {
      html[html.length] = '</object>';
    }
    else
    {
      html[html.length] = '</applet>';
    }

    html[html.length] = '</div>';
    html[html.length] = '</div>';

    var htmlText = html.join('');
    
    ReplaceContent("body_container", htmlText);
}

function CreateThumbnails() {
    showUpdate("Creating thumbnails...");
    tinna.Core.Soap.FrontEnd.CreateThumbnails(OnThumbnailsCreated, OnError);
}

function OnThumbnailsCreated() {
    Message("Success", "Thumbnails created.");
}

/*** select 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;
}


/*** Form validations ***/

function trim(text) {
    return text.replace(/^\s*|\s*$/g, "");
}

function validateForm(formId, missingText, passwordText, incorrectText, expiredText) {
    if(!passwordText)
        passwordText = "";
        
    if(!incorrectText)
        incorrectText = "";
        
    if(!expiredText)
        expiredText = "";
        
    var form = document.getElementById(formId);
    var inputs = form.getElementsByTagName("input");    
    var textareas = form.getElementsByTagName("textarea");
    
    var validated = true;
    
    var validatedInputs = validateElements(inputs, missingText, passwordText, incorrectText, expiredText);
    var validatedTextareas = validateElements(textareas, missingText, passwordText, incorrectText, expiredText);
    
    return (validatedInputs && validatedTextareas);
}

function validateElements(inputs, missingText, passwordText, incorrectText, expiredText) {
    
    var validated = true;
    
    for(var i = 0; i < inputs.length; i++)
    {
        var currInput = inputs[i];
        var parent = currInput.parentNode;
        var label;
        var missing;
        var smallText;
        
        var checkEmail = (currInput.className.indexOf("email") > -1 && !validateEmail(currInput.value));
        var checkCVC = (currInput.className.indexOf("cvc") > -1 && !validateCVCNumber(currInput.value));
        var checkCCN = (currInput.className.indexOf("ccn") > -1 && !validateCreditCardNumber(currInput.value));
        var checkCEXP = (currInput.className.indexOf("cexp") > -1 && !validateCCExpires(currInput.value,currInput.className));
        var checkSSN = (currInput.className.indexOf("ssn") > -1 && !validateSSN(currInput.value));
        var checkEmailConfirm = (currInput.className.indexOf("cmail_") > -1 && !validateEmailConfirm(currInput.value, currInput.className));
        var checkPassword = (currInput.className.indexOf("password_") > -1 && !validatePassword(currInput.value, currInput.className));
        
        //Validate mandatory fields
        if(currInput.className.indexOf("validate") > -1 || currInput.className.indexOf("required") > -1) {
            
            currInput.className = currInput.className.replace("required","validate");
            
            label = parent.getElementsByTagName("label")[0];
            
            if(label != null) {
                var origLabel = (label.getAttribute("orig") != null && label.getAttribute("orig") != "") ? label.getAttribute("orig") : label.innerHTML;
                
                label.innerHTML = origLabel;
                label.className = "";
            }
                       
            if(trim(currInput.value) == "" || checkEmail || checkSSN || checkPassword || checkEmailConfirm || checkCVC || checkCCN || checkCEXP)
            {
                validated = false;
                currInput.className = currInput.className.replace("validate","required");         
                
                label = parent.getElementsByTagName("label")[0];
                var origLabel = (label.getAttribute("orig") != null && label.getAttribute("orig") != "") ? label.getAttribute("orig") : label.innerHTML;                
                var errorLabel = "";
                
                label.setAttribute("orig", origLabel);
                
                if(trim(currInput.value) == "") {
                    errorLabel = origLabel.replace(": *","") + " " + missingText;
                } else if (checkPassword || checkEmailConfirm) {
                    errorLabel = passwordText;
                } else if(checkCCN || checkCVC || checkEmail || checkSSN) {
                    errorLabel = origLabel.replace(": *","") + " " + incorrectText;
                } else if(checkCEXP) {
                    errorLabel = expiredText;
                }
                
                label.innerHTML = errorLabel;
                label.className = "error";
            }
        } //Validate optional fields if they are filled in
        else if((currInput.className.indexOf("optional") > -1 || currInput.className.indexOf("incorrect") > -1) && trim(currInput.value) != "") {
            
            currInput.className = currInput.className.replace("incorrect","optional");
            
            label = parent.getElementsByTagName("label")[0];
            var origLabel = (label.getAttribute("orig") != null && label.getAttribute("orig") != "") ? label.getAttribute("orig") : label.innerHTML;
            
            label.innerHTML = origLabel;
            label.className = "";
            
            if(checkEmail || checkSSN || checkPassword || checkEmailConfirm || checkCVC || checkCCN || checkCEXP)
            {
                validated = false;
                currInput.className = currInput.className.replace("optional","incorrect");         
                
                label = parent.getElementsByTagName("label")[0];
                origLabel = (label.getAttribute("orig") != null && label.getAttribute("orig") != "") ? label.getAttribute("orig") : label.innerHTML;
                
                errorLabel = "";
                
                label.setAttribute("orig", origLabel);
                
                if(incorrectText == "")
                    incorrectText = missingText;

                if(checkSSN || checkCCN || checkCVC) {
                    errorLabel = origLabel.replace(": *","") + " " + incorrectText;
                } else if(checkCEXP) {
                    errorLabel = expiredText;
                } else {
                    errorLabel = origLabel.replace(": *","") + " " + missingText;
                }                
                
                label.innerHTML = errorLabel;
                label.className = "error";
            }
        }
        else {            
            label = parent.getElementsByTagName("label")[0];
            
            if(label != null) {
                var origLabel = (label.getAttribute("orig") && label.getAttribute("orig") != "") ? label.getAttribute("orig") : label.innerHTML;
                
                label.innerHTML = origLabel;
                label.className = "";
            }
        }
    }
    return validated;
}

function validatePassword(value, compareValueObj) {
    var tmp1 = compareValueObj.replace("validate ","");
    var tmp2 = tmp1.replace("required ","");
    var compareValue = document.getElementById(tmp2.replace("password_","")).value;
    
    if(value != compareValue)
        return false;
    else
        return true;
}

function validateSSN(src)
{
    var regex = /[0-9]/g;
    
    if(src.length != 10) {
        return false;
    } else {
        if(regex.test(src))
        {
            return true;
        }
        else {
            return false;
        }
    }
}

function validateEmail(src)
{
    var regex=/([a-zA-Z0-9_-])+(\.{0,1})+([a-zA-Z0-9_-])+([\.][a-zA-Z0-9_-]+){0,1}@{1}([a-zA-Z0-9_-])+(\.{1})+([a-zA-Z0-9]{0,4})+(\.{0,1})+[a-zA-Z]{2,4}$/;

    if(regex.test(src)) {
         return true;
    } else {
        return false;
    }
}

function validateEmailConfirm(value, compareValueObj) {
    var tmp1 = compareValueObj.replace("validate ","");
    var tmp2 = tmp1.replace("required ","");
    var compareValue = document.getElementById(tmp2.replace("cmail_","")).value;
    
    if(value != compareValue)
        return false;
    else
        return true;
}

function validateNumber(obj) {
    var allowed = /[^0-9]/g;
    
    var value = obj.value;
    
    obj.value = value.replace(allowed,'');
}

function validateCreditCardNumber(CCN)
{
    var Valid_Numbers = "0123456789";
    var CreditCard_Numbers = "";
    
    for (var i=0; i < CCN.length; i++)
    {
        Temp = CCN.charAt(i);
        if (Valid_Numbers.indexOf(Temp,0) != -1) { CreditCard_Numbers += Temp; }
    }
    
    var Sum_CreditCard = CreditCard_Numbers.length / 2;
    
    if (Sum_CreditCard < 6.5 || Sum_CreditCard > 8 || Sum_CreditCard == 7)
        return false;
    
    var CreditCard_Even = Math.floor(Sum_CreditCard);
    var CreditCard_Odd = Math.ceil(Sum_CreditCard) - CreditCard_Even;
    var Temp2 = 0;

    for (var i=0; i<CreditCard_Even; i++)
    {
        a = CreditCard_Numbers.charAt(i*2+CreditCard_Odd) * 2;
        Temp2 += a > 9 ? Math.floor(a/10 + a%10) : a;
    }

    for (var i=0; i<CreditCard_Even+CreditCard_Odd; i++) {
        Temp2 += CreditCard_Numbers.charAt(i*2+1-CreditCard_Odd) * 1;
    }

    return (Temp2%10 == 0);
    return false;
}

function validateCVCNumber(src) {
    var cv=/^\d{3}$/;
    
    if (src.length > 3)
    {
        return false;
    }    
    else if (src.length < 3)
    {
        return false;
    }
    else if (src.search(cv)==-1)
    {
        return false;
    }
    else {
        return true;
    }
}

//Checks if the credit card has expired or not
function validateCCExpires(month, yearObj) {
    var yearId = yearObj.replace("validate ","").replace("required ","").replace("cexp_","");
    var year = document.getElementById(yearId).value;

    var today = new Date();
    var currentMonth = (today.getMonth() + 1);
    var currentYear = today.getFullYear();
    
    if(month.substring(0,1) == 0) {
        month = month.substring(1,2);
    }
    
    if(currentYear < year) {
        return true;
    } else if (currentYear == year && currentMonth <= month) {
        return true;
    }
    else {
        return false;
    }
}

//Converts an optional field to a mandatory field
function makeMandatory(fieldToChangeId, nameOfClass) {
    var fieldToChange = document.getElementById(fieldToChangeId);
    fieldToChange.className = nameOfClass;
    
    var label = fieldToChange.parentNode.getElementsByTagName("label")[0];
    
    if(label != null) {        
        if(label.innerHTML.indexOf("*") < 0) {
            label.innerHTML = label.innerHTML + " *";
        }
    }
}

//Converts a mandatory field to an optional field
function makeOptional(fieldToChangeId) {
    var fieldToChange = document.getElementById(fieldToChangeId);
    var parent = fieldToChange.parentNode;
    
    fieldToChange.className = "";
    var label = parent.getElementsByTagName("label")[0];
    
    if(label != null) {        
        label.innerHTML = label.innerHTML.replace(" *","");
    }
    
    if(parent.getElementsByTagName("small").length > 0) {
        var smallText = parent.getElementsByTagName("small")[0];
        parent.removeChild(smallText);
    }
}

//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);
    }
}

//Clear a form on cancel
function clearForm(form) {
    var formContainer = document.getElementById(form);
    var formValues = formContainer.getElementsByTagName("input");
        
    for(var i = 0; i < formValues.length; i++) {
        var input = formValues[i];
        
        if(input.type == "text" || input.type == "hidden" || input.type == "password") {
            input.value = "";
        } else if(input.type == "checkbox") {
            input.checked = false;
        }
    }
}



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');
    
    var fadeSlow = new Fx.Style(message, 'opacity', {
		duration	: 500,
		transition	: Fx.Transitions.linear,
		onComplete	: function(){
			RemoveHoverWindow("message");
		}
	});
	
	fadeSlow.start(1,0);
}

function fadeContainer(container, start, finish) {
    var fader = $(container);
    
    var fadeSlow = new Fx.Style(fader, 'opacity', {
		duration	: 500,
		transition	: Fx.Transitions.linear,
		onComplete	: function(){
			
		}
	});
	
	fadeSlow.start(start,finish);
}


/*** 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) {
        updateContainer = document.createElement("div");
        updateContainer.setAttribute("id","update_container");
        document.body.insertBefore(updateContainer, document.body.firstChild);
    }
    
    var updateAnimation = document.getElementById("update_animation");
    
    if(!updateAnimation) {
        updateAnimation = document.createElement("div");
        updateAnimation.setAttribute("id","update_animation");
        updateContainer.insertBefore(updateAnimation, updateContainer.firstChild);
    }
    
    updateAnimation.innerHTML = text;
    
    if(updateAnimation.className == "hide") {        
        updateAnimation.className = "";
        
        var message = $('update_animation');
        var fadeSlow = new Fx.Style(message, 'opacity', {
            duration	: 200,
            transition	: Fx.Transitions.linear,
            onComplete	: function(){
            }
        });

        fadeSlow.start(0,1);    
    }
    
    updateTimer = setTimeout("stopUpdateTimer()",updateMinTime);
}

function stopUpdateTimer() {
    updateCanStop = true;
    clearTimeout(updateTimer);
    
    if(updateFinished)
    {
        stopUpdateWindow();
    }
}

function stopUpdateWindow() {
    updateFinished = true;
    
    if(updateCanStop) {
        var updateContainer = document.getElementById("update_animation");
        
        if(updateContainer) {
            var message = $('update_animation');
    
            var fadeSlow = new Fx.Style(message, 'opacity', {
		        duration	: 500,
		        transition	: Fx.Transitions.linear,
		        onComplete	: function(){
			        updateContainer.className = "hide";
		        }
	        });
	
	        fadeSlow.start(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 hash = location.hash;
    
    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 {
                GetImageCloud();
            }            
        } 
        else if(hash.indexOf("#img") > -1) {
            if(hash.indexOf("#img:") > -1) {
                var photo = hash.replace("#img:","");
                
                OpenImage(photo);
            } else {
                GetImageCloud();
            }            
        }
        else if(hash.indexOf("#blog") > -1) {
            if(hash.indexOf("#blog:") > -1) {
                var page = hash.replace("#blog:","");
                
                if(page.indexOf(":") > -1) {
                    //Split page up into page and article id
                    var articleProps = page.split(":");
                    
                    if(articleProps.length > 1) {
                        ReadArticle(articleProps[1])
                    }
                }
                else {
                    GetBlog(page);
                }
            } else {
                GetImageCloud();
            }
        } else {
            GetImageCloud();
        }
    } else {
        GetImageCloud();
    }
}

window.onload = function(e) {
    GetMenu();
    AjaxHistory();
    CheckPermaLink();
    
    //_historyTimer = setInterval("ObserveHistory()", 5000);   
}

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;}