/**
* Heavy Utilities, contains all global functions and objects. mapped to the Heavy global var
* uses function scoping to keep everything out of the global scope.
* @author wstuckey
* $Id$
*/
document.getElementsByTagName('html')[0].className = "js"; // let the css know this is a js enabled browser
var Heavy = (typeof(Heavy) != "object") ? {} : Heavy;

var debug;
var log = function() {
    if (debug === false) return;
    Array.prototype.unshift.call(arguments, "[JS] - "); // append the [JS] to the front of all my logs ;)
    if (window.console && console.firebug) {
        return window.console.log.apply(window, arguments);
    } else if (window.console) { // safari logging.
        var s = "";
        for (var i = 0, arg; arg = arguments[i]; i++) {
            s += arg.toString() + " ";
        }
        return window.console.log(s);
    }
    return false; // don't break IE
};
$.extend(Heavy, {log: log}); // publicize this log method.
$.extend(Heavy, {
    log : log,
    /**
    * Cookies! Constructor gets cookie value by default
    * @constructor
    * @param {String} name This is the name of your cookie
    */
    Cookie : function(name, options) {
        var options = options || {};

        /**
        * Get the cookie and return a string value
        * @return String
        */
        this.get = function() {
            var cookies = document.cookie.split(';');
            for (var i = 0, c; c = cookies[i]; i++) {
                c = c.replace(/^\s+/, ""); //trim the front of the string
                c = c.split("=");
                if(c[0] == this.name) {
                    return this.value = decodeURIComponent(c[1]);
                }
            }
            return null;
        };

        /**
        * Sets the scalar value of the cookie, also performs a save.
        * @return Void
        * @param value {String} Value of the cookie to be set
        */
        this.set = function(value) {
            this.value = value;
            return this.save();
        };

        this.push = function(v) {
            var valueArray = this.value.split("|");
            if (valueArray[0] !== "") {
                valueArray.push(v);
            } else {
                return this.set(v);
            }
            return this.set(valueArray.join("|"));
        };

        this.pop = function() {
            var valueArray = this.value.split("|");
            return valueArray.pop();
        };

        this.getList = function() {
            return this.value.split("|");
        };

        this.setPath = function(path) {
            return this.path = '; path=' + path;
        };
        this.setDomain = function(domain) {
            return this.domain = '; domain=' + domain;
        };
        this.setExpiration = function(expiration) {
            if (expiration === 0) return this.expires = "";
            date = new Date();
            date.setTime(date.getTime() + (expiration * 24 * 60 * 60 * 1000));
            return this.expires = '; expires=' + date.toGMTString(); // use expires attribute, max-age is not supported by IE
        };

        this.remove = function() {
            this.setExpiration(-1);
            this.value = null;
            return this.save();
        };

        this.save = function() {
            return document.cookie = [this.name, '=', encodeURIComponent(this.value), this.expires, this.path, this.domain].join('');
        };


        // setup internal properties
        this.name       = name;
        this.value      = options.value || "";
        this.expires    = this.setExpiration(options.expires || 0);
        this.path       = this.setPath(options.path || "/");
       // this.domain     = this.setDomain(options.domain || Host.DOMAIN);

        if (options.value) {
            this.save();
        } else {
            this.get();
        };
    },
    hasCookie: function() {
        var c = new Heavy.Cookie("test");
        c.set(Math.random());
        var v = c.get();
        c.remove();
        return v !== null ? true : false;
    },
    /**
    * Stage Dimensions
    */
    Stage : {
        width: function() {
            return document.documentElement.clientWidth;
        },
        height: function() {
            return self.innerHeight || document.documentElement.clientHeight;
        },
        scrollLeft: function() {
            return document.documentElement.scrollLeft || document.body.scrollLeft;
        },
        scrollTop: function() {
            return document.documentElement.scrollTop || document.body.scrollTop;
        }
    },
    /**
    * Alert functions builds and displays a modal alert, confirm, or login window.
    * Can easily be adapted to display different types of modal windows ie: iframed content or whatever.
    *
    * @returns Void
    * @param {Object} options A key value object representing all the available options
    *      @option {String} type Specifies the modal type, defaults to 'alert'. Currently supports 'alert', 'confirm', and 'login'
    *      @option {String} title Title of the modal window, defaults to a empty string except for login windows.
    *      @option {String} message Message for your confirm or alert dialog. Only applies to those two types.
    *      @option {Function} ok Callback for the "Ok" button. Fired "onclick".
    *      @option {Function} cancel Callback for the "Cancel" button. Fired "onclick".
    *      @option {Function} submit Callback for the "Submit" button, only applies to "login" type dialog. Fires on login success.
    *      @option {Boolean} grey If set to true the entire window behind the modal dialog will be greyed out. Defaults to true.
    *      @option {Boolean} scroll Prevents modal position from updating on window scroll.
    *      @option {Boolean} resize Prevents modal position from updating on window resize.
    */
    Alert : function(options) {
        // return if already visible
        if ($("#alert:visible")[0]) return;
        // setup default variables
        var self     = this;
        this.type    = options.type     || "alert";
        this.title   = options.title    || "";
        this.message = options.message  || "";
        // set up window options
        this.grey    = (options.grey   !== null) ? options.grey   : true;
        this.scroll  = (options.scroll !== null) ? options.scroll : true;
        this.resize  = (options.resize !== null) ? options.resize : true;
        this.requestParameters = options.requestParameters  || [];

        var _build = function() {
            return $("<div id='alert'>").append("<div id='alert-content'><div id='alert-buttons'></div></div>").appendTo("body").hide();
        };
        var _center = function(height) {
            // center on page
            var h = (typeof height == "number") ? height : self.alert.height();
            self.alert.css({
            "top" : (.5 * (Heavy.Stage.height() - h) + Heavy.Stage.scrollTop()),
            "left" : (.5 * (Heavy.Stage.width() - 301) + Heavy.Stage.scrollLeft()),
            "z-index" : "10001"
            });
        };
        var _show = function() {
            // append the iframe overlay if self.grey is true
            if (self.grey == true) {
                if (!$("#alert-grey")[0]) self.alert.before("<iframe id='alert-grey'>");
                $("#alert-grey").show();
                _grey = function() {
                    $("#alert-grey").css({
                    "top" : Heavy.Stage.scrollTop(),
                    "left" : 0,
                    "width" : Heavy.Stage.width(),
                    "height" : Heavy.Stage.height(),
                    "z-index" : "10000"
                    });
                };
                _grey();
                if (self.scroll == true) $(window).resize(_grey);
                if (self.resize == true) $(window).scroll(_grey);
            }
            // pass in a default height if
            if (self.alert.filter(":hidden")[0]) {
                _center(250);
            } else {
                _center();
            }
            // alert
            self.alert.addClass(self.type).show();
            // default $("#alert-buttons .default")[0].focus();
            if (self.scroll == true) $(window).scroll(_center);
            if (self.resize == true) $(window).resize(_center);
        };
        var _hide = function() {
            self.alert.hide().removeClass(self.type);
            $(window).unbind("scroll", _center).unbind("resize", _center);
            if ($("#alert-grey")[0]) $("#alert-grey").remove();
            $("#alert h1, #alert p, #alert-join-link").remove();
            $("#alert-buttons").html("");
        };
        // get alert
        this.alert = $("#alert")[0] ? $("#alert") : _build();
        // set up the alert for the specific type
        switch(this.type) {
            case "login":
            this.title = (this.title === "") ? "Login to Heavy" : this.title;
            // build the login form
            // this is a little insane, please forgive me :)
            var loginForm = $("<form action='/pages/login.php' id='alert-login'>") //  form
            .add("<div id='loginPasswordDiv'><label for='alert-password'>Password</label><input id='alert-password' type='password' /></div>")
            .add("<div id='loginEmailDiv'><label for='alert-email'>E-mail Address</label><input id='alert-email' type='text' class='default' /></div>");
            var buttons = $("<a href='#' id='alert-cancel' class='button'><span>Cancel</span></a>").add("<a href='#' id='alert-submit'  class='button'><span>Submit</span></a>").appendTo("#alert-buttons");
            // append the signup link
            $("#alert-content").append("<p id='alert-join-link'><a href='/signup'>Not a member? Click here to join.</a></p>");
            // do a simple front end validation on the form.
            var _validate = function() {
                var error = $("#alert-login-error")[0] ? $("#alert-login-error") : $("<p id='alert-login-error'>").appendTo(loginForm[0]);
                var r = /[\-a-z0-9\_]+(\.[\-a-z0-9\_]+)*\@[\-a-z0-9\_]+(\.[\-a-z0-9]+)+/i;
                if ($("#alert-email").val() === "") {
                    error.text("Email Address is required.");
                    return false;
                }
                if (!r.test($("#alert-email").val())) {
                    error.text("E-mail is invalid.");
                    return false;
                }
                if(!$("#alert-password").val()) {
                    error.text("Password is required.");
                    $("#alert-password").focus();
                    return false;
                }
                error.text(" ");
                return true;
            };
            buttons.bind("click", function() {
                if(this.id == "alert-submit" && _validate()){
                    Heavy.LoginManager.login({
                        username: $("#alert-email").val(),
                        password: $("#alert-password").val(),
                        success: function(param) {
                            _hide();
                            loginForm.remove();
                            if (options.submit){
                                options.submit.apply(this, self.requestParameters); // fire submit callback
                            }
                        },
                        error: function(e) {
                            var error = $("#alert-login-error")[0] ? $("#alert-login-error") : $("<p id='alert-login-error'>").appendTo(loginForm[0]);
                            error.text(e);
                        }
                    });
                } else if(this.id == "alert-cancel"){
                    loginForm.remove(); //remove the form from the DOM;
                    _hide();
                    if (typeof options.cancel == "function") options.cancel(); // cancel callback
                }
                return false;
            });
            loginForm.prependTo($("#alert-content")[0]);
            $("<h1>").text(this.title).prependTo($('#alert-content')[0]);
            $("#alert-email").focus();
            break;
            case "confirm":
            var message = $("<p>").prependTo($('#alert-content')[0]);
            var title = $("<h1>").prependTo($('#alert-content')[0]);
            var buttons = $("<a href='#' id='alert-cancel' class='button'><span>Cancel</span></a>").add("<a href='#' id='alert-ok' class='button default'><span>Ok</span></a>").appendTo("#alert-buttons");
            buttons.bind("click", function() {
                _hide();
                self.alert.removeClass("confirm");
                if (this.id == "alert-ok" && typeof options.ok == "function") options.ok(); // fire ok call back
                if (this.id == "alert-cancel" && typeof options.cancel == "function") options.cancel(); // fire cancel call back
                return false;
            });
            message.text(this.message);
            title.text(this.title);
            this.alert.addClass("confirm");
            break;
            case "alert" :
            default:
            var message = $("<p>").prependTo($('#alert-content')[0]);
            var title = $("<h1>").prependTo($('#alert-content')[0]);
            var buttons = $("#alert-ok")[0] ? $("#alert-ok") : $("<a href='#' id='alert-ok' class='button default'><span>Ok</span></a>").appendTo("#alert-buttons");
            buttons.bind("click", function() {
                _hide();
                self.alert.removeClass("alert");
                if (this.id == "alert-ok" && typeof options.ok == "function") options.ok(); // fire ok callback
                return false;
            });
            message.html(this.message);
            title.text(this.title);
            this.alert.addClass("alert");
            break;
        };
        _show();
    },
    LoginManager : {
        loginUrl: "/pages/login.php",
        loggedIn: null,
        isLoggedIn : function() {
            if (this.loggedIn) return this.loggedIn;
            var loginCookie = new Heavy.Cookie("mry");
            return this.loggedIn = (loginCookie.value) ? true : false;
        },
        login : function(params) {
            if (!params.username || !params.password) return false;
            $.ajax({
                url: this.loginUrl,
                data: "username="+ params.username + "&password=" + params.password,
                type: "POST",
                success: function(req) {
                    // parse response
                    var loggedIn = req.split("&")[0].split("=")[1];
                    var message = req.split("&")[1].split("=")[1];
                    if (loggedIn == "true") {
                        if(params.success){
                            params.success(unescape(message)); // fire success callback
                        }
                        Heavy.Navigation.check();
                    } else {
                        if(params.error) params.error(unescape(message)); // fire error callback
                    }
                }
            });
        },
        displayLogin : function(isGrey, doScroll, callback) {
            if (isGrey == true && MediaPlayerManager) MediaPlayerManager.greyPage(1);
            Heavy.Alert({type: 'login', grey: false, scroll: doScroll, submit: function() {
                if (callback) callback();
                if (MediaPlayerManager) MediaPlayerManager.greyPage(0);
            }, cancel: function() {
                if (MediaPlayerManager) MediaPlayerManager.greyPage(0);
            }});
        }
    },
    Navigation : {
        /**
        * Update user status links with personalized info, only if the user
        * is logged-in.  This is also used to refresh links when user signs
        * in via modal dialogs.
        */
        check : function(callback) {
            var loggedIn = Heavy.LoginManager.isLoggedIn(),
            navId = 'meta-nav',
            navNode = $("#"+navId);
            if (loggedIn) {
                navNode.hide();
                $.get("/pages/header_refresh.php", {section: navId, nocache: 1}, function(data) {
                    navNode.html(data).show();
                });
            }
            if (callback) {
                callback();
            }
            return;
        }
    },
    Validation : function(options){
        var self     = this;
        var re       = '';
        this.val     = options.value  || "";
        this.type    = options.type   || "";

        switch(this.type){
            case 'email' : // info@heavy.com
            re = /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/;
            break;
            case 'phone' : // 222-333-4444
            re = /^[2-9]\d{2}-\d{3}-\d{4}$/;
            break;
            case 'image' : // new-pic_company.jpg gif png
            re = /^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$/;
            break;
            case 'multimedia' : // heavy.swf mov wma mpg mp3 mp4 wav
            re = /^[a-zA-Z0-9-_\.]+\.(swf|mov|wma|mpg|mp3|mp4|wav)$/;
            break;
        }
        if (!this.val.match(re)){
            return (false);
        }else{
            return (true);
        }

    }

});

/**
* Pop up function
*/
$.extend(Heavy, {
    launchwin : function(winurl,winname,winfeatures) {
        var showwin = window.open(winurl, winname, winfeatures);
        if (showwin) {
            showwin.focus();
        } else {
            Heavy.Alert({title: 'Sorry!', message: 'You need to disable your popup blocker first!'});
        }
    }
});

/**
*  Count left function
* function parameters are: field - the string field, count - the field for remaining
* characters  number and max - the maximum number of characters  
*/ 
 
$.extend(Heavy, {
    countLeft : function(field, count, max) {
    // if the length of the string in the input field is greater than the max value, trim it 
    if (field.value.length > max){
        field.value = field.value.substring(0, max);
    }else{
        // calculate the remaining characters  
        count.value = max - field.value.length;
    }
    }
});

$.extend(Heavy, {
    addTag : function(field, count, max) {
    // if the length of the string in the input field is greater than the max value, trim it
    if (field.value.length > max){
        field.value = field.value.substring(0, max);
    }else{
        // calculate the remaining characters
        count.value = max - field.value.length;
    }
    }
});

$.extend(Heavy, {
    jumpToPage : function(frmName) {
		eval('document.'+frmName).submit();
    }
});

$.extend(Heavy, {
    getConfirmation : function(msg,url) {
		if(confirm(msg)){
    		location.href=url;
	    }
	    return false;
    }
});

$.extend(Heavy, {
    appendTag : function() {
    	if($("#txtTag").val()!="") {
			var tag_set=$("#txtTag").val();
			var arr_temp=tag_set.split(",");
			for(i=0;i<arr_temp.length;i++) {
				if(arr_temp[i]!="") {
			        $("#tagParent").append("<span id='"+arr_temp[i]+"'>&nbsp;<a href='Javascript:void(0)' onclick=Heavy.removeTag('"+arr_temp[i]+"');><img src='/media/images/delete.jpg' border='0' valign='middle'></a>"+arr_temp[i]+"</span>");
    			    $("#tag_ids").val($("#tag_ids").val()+","+arr_temp[i]);
        			$("#txtTag").val('');
        			$("#txtTag").focus();
				}
			}
	    }else {
    	    alert("Please enter tag name");
        	$("#txtTag").focus();
    	}

	}
});

$.extend(Heavy, {
    removeTag : function(strName) {
    	$("#"+strName).remove();
		strName=strName.replace('_',' ');
		if($("#tag_ids").val().indexOf(",") >0)	
			$("#tag_ids").val($("#tag_ids").val().replace(","+strName,""));
		else
			$("#tag_ids").val($("#tag_ids").val().replace(strName,""));
	}
});

$.extend(Heavy, {
    setAction : function(strAction) {
    	$("#action").val(strAction);
		$("#post_publish").val("1");
		var ed = tinyMCE.get("posts_content");
 	    comments = ed.getContent();
    	$("#posts_content_dummy").val(comments);
		//alert($("#posts_content_dummy").val());

	}
});
$.extend(Heavy,{
	initCalendar : function(){
		$(document).ready(function (){
        $("#published_date").datepicker({ dateFormat: 'yy-mm-dd' });
        $("#expiry_date").datepicker({ dateFormat: 'yy-mm-dd'});
		});
	}
});
if(typeof(myurl)=="undefined") myurl="";
$.extend(Heavy, {    
	initTinyMCE: function (control_name){
		tinyMCE.init({
        // General options
        //mode : "textareas",
        mode :"exact",
        elements:control_name,
		extended_valid_elements : "iframe[src|width|height|name|align|border|frameborder|framespacing|scrolling]",
        theme : "advanced",
                plugins :"safari,pagebreak,template,insertdatetime,preview",
        // Theme options
        theme_advanced_buttons : "bold,italic,underline,strikethrough",
                theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        content_css : "/media/js/tiny_mce/css/content.css",

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "/media/js/tiny_mce/lists/template_list.js",
        external_link_list_url : "/media/js/tiny_mce/lists/link_list.js",
                external_image_list_url : myurl+"/admin/getimages",
        media_external_list_url : "/media/js/tiny_mce/lists/media_list.js",
                relative_urls : false,
                convert_urls :false
    });

		
	}	
});
$.extend(Heavy,{
	replaceChar :function (src,destn,find,replace){
		 var tempstr=$(src).val();
	    tempstr=tempstr.replace(find,replace);
    	$(destn).val(tempstr);
	}
});

$.extend(Heavy, {
	titleFormat : function(url) {
		var exp= /^\s.*|.*\s$/;
		var exp_new=/\s{2,}/;

		if(url.match(exp)!=null ){
			alert("No space is allowed at the beggining and at the end of the title");
			return false;
		}

		if(url.match(exp_new)!=null){
			alert("No 2 consequtive spaces in  title/permalink ");
			return false;
		}

		return true;
	}
});

$.extend(Heavy, {
	urlFormat : function(url) {
		var exp1=/\s{2,}/;
		var exp2=/^[^A-Z]*$/;
		var exp3=/\-{2,}/;
		if(url.match(exp1)!=null){
			alert("No 2 consequtive spaces allowed in permalink ");
			return false;
		}
		if(url.match(exp3)!=null){
			alert("No 2 consequtive hyphens allowed in  permalink ");
			return false;
		}
		if(url.match(exp2)==null){
			alert("No capital letters allowed in  permalink ");
			return false;
		}
		return true;
	}
});