function trim(str) {
    var temp = str.replace(/^\s+|\s+$/g, '\n');
	return str.replace(/^\s+|\s+$/g, '') ;
}

String.prototype.unescapeHtml = function () {
    var temp = document.createElement("div");
    temp.innerHTML = this;
    var result = temp.childNodes[0].nodeValue;
    temp.removeChild(temp.firstChild)
    return result;
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var Downloader = {
    _init : function(){
        if ($("#downloader-frame").size() == 0)            
                $("<iframe id=\"downloader-frame\" width=\"0\" height=\"0\" style=\"display:none\" />").appendTo($("body:first"));
        return $("#downloader-frame");
    },
    Download : function(file, type, indirect){
        downloadFrame = this._init();
        filetype = "";
        if (type) filetype = "&filetype=" + type;
        if (typeof indirect == "undefined") indirect = true;        
        // download is indirect, require using controller
        if (indirect) downloadFrame.attr("src", "/index.php?r=download/get&file=" + file + filetype);
        // download is direct, give the link directly
        else {
            downloadFrame.attr("src", file);
        }
		if (typeof pageTracker != "undefined"){
            pageTracker._trackPageview('/downloads/'+file);
        }
    }
}

$(document).ready(function(){

    $("[_link]").click(function(){
        window.location.href = $(this).attr("_link");
    });

    $("[_tag=profile_link]").css("cursor", "pointer").click(function(){
        window.location.href = "index.php?r=user/show&id=" + $(this).closest("[_userid]").attr("_userid");
    });

    $("img", "div.flags").css("cursor", "pointer").click(function(){
        $.ajax({
            url : 'index.php?r=user/setLanguage',
            data : {
                lang : $(this).attr("_lang")
            },
            success : function(data){
                if (data == '1'){
                    window.location.reload();
                } else {
                    window.location.reload();
                }
            }
        });
    });
	var Y = YUI();
    Y.use('node','imageloader',function(Y){
    	var flags = Y.all('div[_lang]');
    	var flagsGroup = new Y.ImgLoadGroup({ timeLimit: 0.1 });
    	flags.each(function(n,i){
    		n.set('id',Y.stamp(n));
    		flagsGroup.registerImage({ domId: n.get('id'), bgUrl: n.getAttribute('_src'), isPng: true });
    		n.set('innerHTML','');
    		n.setStyle('width','16px');
    		n.setStyle('height','11px');
    	});
    	$("div.flags div[_lang]").css("cursor", "pointer").click(function(){
            $.ajax({
                url : 'index.php?r=user/setLanguage',
                data : {
                    lang : $(this).attr("_lang")
                },
                success : function(data){
                    if (data == '1'){
                        window.location.reload();
                    } else {
                        window.location.reload();
                    }
                }
            });
        });
    });
    $("a[_lang]", "div.footer").css("cursor", "pointer").click(function(){
        $.ajax({
            url : 'index.php?r=user/setLanguage',
            data : {
                lang : $(this).attr("_lang")
            },
            success : function(data){
                if (data == '1'){
                    window.location.reload();
                } else {
                    window.location.reload();
                }
            }
        });
    });

    Emoticon.InitPreview();
    FriendList.InitStatus();

    var Helper = {
        AJAX_TYPE_TEXT : 0,
        AJAX_TYPE_TEXTAREA : 1,
        AJAX_TYPE_SELECT : 2,
        AJAX_TYPE_CHECKBOX : 3,
        AJAX_TYPE_DATE : 4,
        AJAX_TYPE_SUB_SELECT : 5,

        AjaxUpdate : function(el, callback_success, callback_failed){
			$.ajax({
                url : "index.php?r=" + $(el).attr("_controller"),
                type : "post",
                data : {
                    field : $(el).attr("_field"),
                    data : $(el).val()
                },
                beforeSend : function(){
                    el.attr("disabled", "disabled");
					//$("input",el).attr("disabled", "disabled");
                    el.closest("[_editableHolder]").attr("_updating", "1");
                },
                success : function(data){
                    el.closest("[_editableHolder]").attr("_updating", "0");
                    el.removeAttr("disabled");
					//$("input",el).removeAttr("disabled");
                    if (data == 1){
                        EventLog.Info("Information has been updated.");
                        if (callback_success) callback_success(data);
                    } else if (data == 0){
                        if (callback_failed) callback_failed(data);
                    }
                },
                error : function(){
                    el.closest("[_editableHolder]").attr("_updating", "0");
                    el.removeAttr("disabled");
                    if (callback_failed) callback_failed();
                }
            });
        },

        AjaxUpdateInit : function(el, type){

            if (el.attr("_binded")) return true;

            switch(type){
                case Helper.AJAX_TYPE_TEXT:
                    // blur events
                    $(el).blur(function(evt){
                        holder = el.closest("[_editable]");
                        holder.text(holder.attr("_currentValue"));
                        el.remove();
                    });
                    // init keyboard events
                    $(el).keydown(function(evt){
                        switch(evt.keyCode){
                            case 9: // Tab

                                tabIndex = parseInt(el.closest("[_editableHolder]").attr("_tabIndex"));
                                nextTabIndex = tabIndex + (evt.shiftKey? -1: 1);
                                nextField = $("[_editableHolder][_tabIndex="+ nextTabIndex +"][_updating=0]");

                                if (nextField.size() == 0) return false;

                                nextField.trigger("click");
                                Helper.AjaxUpdate($(this), function(data){
                                    holder = el.closest("[_editable]");
                                    text = el.val();
									if(tabIndex=="6"){
                                        text = text + "cm";
                                    }
                                    dynamic = holder.attr("_dynamicResource");
                                    holder.empty().text(text);
                                    el.remove();
                                    $("[_dynamicResource=" + dynamic + "]").not(holder).text(text);
                                }, function(data){
                                    // @todo to do later
                                });
                                return false;
                                break;

                            case 13: // Enter
                                Helper.AjaxUpdate($(this), function(data){
                                    holder = el.closest("[_editable]");
                                    text = el.val();
                                    if(trim(text)==0){
                                        if(el.closest("tr").attr("_tabIndex")==-1)
                                            text = "[How are you feeling today?]";
                                        else
                                            text = "[click here to edit]"
                                    }
									if(el.closest("tr").attr("_tabindex")==6&&text!="[click here to edit]")
                                        text = text + "cm";
                                    dynamic = holder.attr("_dynamicResource");
                                    holder.empty().text(text);
                                    el.remove();
                                    $("[_dynamicResource=" + dynamic + "]").not(holder).text(text);
                                    EventLog.Info("Information has been updated.");
                                }, function(data){
                                    // @todo to do later
                                });
                                break;
                            case 27: // Escape
                                holder = el.closest("[_editable]");
                                holder.text(holder.attr("_currentValue"));
                                el.remove();
                                break;
                            default : break;
                        }
                    });
                    break;
                case Helper.AJAX_TYPE_TEXTAREA:

                    // blur
                    $(el).blur(function(evt){
                        holder = el.closest("[_editable]");
                        text = el.val();
                        holder.attr("_currentValue",holder.attr("_currentValue").replace(/<BR>/g, '\n').replace(/<br>/g, '\n').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
                        if($.trim(holder.attr("_currentValue"))!=$.trim("[click here to edit]")&&$.trim(holder.attr("_currentValue"))!=$.trim(text))
                        {
                            Helper.AjaxUpdate($(this), function(data){
                                holder = el.closest("[_editable]");
                                text = el.val();
                                if($.trim(text)==0){
                                    text = "[click here to edit]";
                                }
                                else
                                    text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<BR />");
                                dynamic = holder.attr("_dynamicResource");
                                holder.empty().html(text); //.removeAttr("_currentValue");
                                holder.attr("_currentValue", el.html());
                                el.remove();
                                $("[_dynamicResource=" + dynamic + "]").not(holder).html(text);
                            }, function(data){
                                // @todo to do later
                            });
                        }
                        else{
                            text = el.val();
                            if($.trim(text)==0){
                                text = "[click here to edit]";
                            }
                            else
                                text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<BR />");
                            holder.empty().html(text);
                            el.remove();
                        }
                        //holder = el.closest("[_editable]");
                        //holder.html(holder.attr("_currentValue").replace(/<BR>/g, '<BR />'));
                        //el.remove();
                    });

                    // init keyboard events
                    $(el).keydown(function(evt){
                        switch(evt.keyCode){
                            case 9: // Tab
                                tabIndex = parseInt(el.closest("[_editableHolder]").attr("_tabIndex"));
                                nextTabIndex = tabIndex + (evt.shiftKey? -1: 1);
                                nextField = $("[_editableHolder][_tabIndex="+ nextTabIndex +"]");

                                if (nextField.size() == 0) return false;

                                nextField.trigger("click");
                                holder = el.closest("[_editable]");
                                text = el.val();
                                holder.attr("_currentValue",holder.attr("_currentValue").replace(/<BR>/g, '\n').replace(/<br>/g, '\n').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
                                if($.trim(holder.attr("_currentValue"))!=$.trim("[click here to edit]")&&$.trim(holder.attr("_currentValue"))!=$.trim(text))
                                {
                                    Helper.AjaxUpdate($(this), function(data){
                                        holder = el.closest("[_editable]");
                                        text = el.val();
                                        if($.trim(text)==0){
                                            text = "[click here to edit]";
                                        }
                                        else
                                            text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<BR />");
                                        dynamic = holder.attr("_dynamicResource");
                                        holder.empty().html(text); //.removeAttr("_currentValue");
                                        holder.attr("_currentValue", el.html());
                                        el.remove();
                                        $("[_dynamicResource=" + dynamic + "]").not(holder).html(text);
                                    }, function(data){
                                        // @todo to do later
                                    });
                                }
                                else{
                                    text = el.val();
                                    if($.trim(text)==0){
                                        text = "[click here to edit]";
                                    }
                                    else
                                        text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<BR />");
                                    holder.empty().html(text);
                                    el.remove();
                                }
                                return false;
                                break;
                            case 13: // Enter
                                if (evt.ctrlKey){
                                    holder = el.closest("[_editable]");
                                    text = el.val();
                                    holder.attr("_currentValue",holder.attr("_currentValue").replace(/<BR>/g, '\n').replace(/<br>/g, '\n').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
                                    if($.trim(holder.attr("_currentValue"))!=$.trim("[click here to edit]")&&$.trim(holder.attr("_currentValue"))!=$.trim(text))
                                    {
                                        Helper.AjaxUpdate($(this), function(data){
                                            holder = el.closest("[_editable]");
                                            text = el.val();
                                            if($.trim(text)==0){
                                                text = "[click here to edit]";
                                            }
                                            else
                                                text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<BR />");
                                            dynamic = holder.attr("_dynamicResource");
                                            holder.empty().html(text); //.removeAttr("_currentValue");
                                            holder.attr("_currentValue", el.html());
                                            el.remove();
                                            $("[_dynamicResource=" + dynamic + "]").not(holder).html(text);
                                        }, function(data){
                                            // @todo to do later
                                        });
                                    }
                                    else{
                                        text = el.val();
                                        if($.trim(text)==0){
                                            text = "[click here to edit]";
                                        }
                                        else
                                            text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<BR />");
                                        holder.empty().html(text);
                                        el.remove();
                                    }
                                }
                                else{
                                    // insert new line
                                    //$(el).val($(el).val() + '\n');
                                    $(el).val($(el).val());
                                    return true;
                                }


                                break;
                            case 27: // Escape
                                holder = el.closest("[_editable]");
                                holder.html(holder.attr("_currentValue").replace(/<BR/g, '<BR />'));
                                el.remove();
                                break;
                            default : break;
                        }
                    });

                    break;
                case Helper.AJAX_TYPE_SELECT:
                    $(el).blur(function(){
                        el.hide().prev("span").show();
                    });
                    $(el).keydown(function(evt){

                        // return false;

                        switch(evt.keyCode){
                            case 9: // Tab
                                tabIndex = parseInt(el.closest("[_editableHolder]").attr("_tabIndex"));
                                nextTabIndex = tabIndex + (evt.shiftKey? -1: 1);
                                nextField = $("[_editableHolder][_tabIndex="+ nextTabIndex +"]");
                                if (nextField.size() == 0) return false;
                                nextField.click();
                                el.hide().prev("span").show();
                                return false;
                                break;
                            default :
                                break;
                        }
                    });
                    $(el).keyup(function(evt){
//                        if (evt.keyCode == 9) return false;
//
//                        else Helper.AjaxUpdate($(this), function(data){
//                            holder = el.closest("[_editable]");
//                            text = $(":selected", el).attr("_display");
//                            dynamic = holder.attr("_dynamicResource");
//                            $("[_dynamicResource=" + dynamic + "]").not(holder).text(text);
//                            el.hide().prev("span").show().text($(":selected", el).attr("_display"));
//                        }, function(data){
//                            // @todo to do later
//                        });
                        // handle change by keyboard
                    });
                    $(el).change(function(){
                        Helper.AjaxUpdate($(this), function(data){
                            holder = el.closest("[_editable]");
                            text = $(":selected", el).attr("_display");
                            dynamic = holder.attr("_dynamicResource");
                            $("[_dynamicResource=" + dynamic + "]").not(holder).text(text);
                            el.hide().prev("span").show().text($(":selected", el).attr("_display"));
                        }, function(data){
                            // @todo to do later
                        });
                    });
                    break;
                case Helper.AJAX_TYPE_DATE :
                    $(el).bind("fire", function(){
                        localField = el.closest("[_editable]");
                        Helper.AjaxUpdate($(this), function(data){
                            el.datepicker('destroy').remove();
                            // holder = el.closest("[_editable]").text(el.val());
                            localField.text(localField.attr("_currentValue"))
                        }, function(data){
                            el.datepicker('destroy').remove();
                            localField.text(localField.attr("_currentValue"))
                            // @todo to do later
                        });
                    });
                    $(el).blur(function(evt){
                        // console.info(evt);
                        // if (evt.target)
                        // el.datepicker('destroy').remove();
                        // localField.text(localField.attr("_currentValue"))
                    });
                    $(el).keydown(function(evt){
                        switch(evt.keyCode){
                            case 9: //tab
                                break;
                            case 13: //enter
                                localField = el.closest("[_editable]");
                                el.datepicker('destroy');
                                Helper.AjaxUpdate($(this), function(data){
                                    el.remove();
                                    // holder = el.closest("[_editable]").text(el.val());
                                    localField.text(localField.attr("_currentValue"))
                                }, function(data){
                                    el.remove();
                                    localField.text(localField.attr("_currentValue"))
                                    // @todo to do later
                                });
                                return false;
                                break;
                            case 27: // esc
                                el.datepicker('destroy').remove();
                                localField.text(localField.attr("_currentValue"))
                                break;
                            default: break;
                        }
                    });
                    break;
                case Helper.AJAX_TYPE_CHECKBOX:
					checkBoxes = ($("input",el));
                    if($(this).attr("checked"))
                        $(this).removeAttr("checked");
                    else
                        $(this).attr("checked","checked");
					var newCheckedBox;
					$(checkBoxes).click(function(evt){
                        $(this).attr("disabled","disabled");
                        checkBoxes = $("input",$(this).closest("tr"));
						var codeList = "";
						var languageName = "";
                        var count = 0;
                        var boxes = $(this).closest("div").attr("value").split(" ");
						for(i = 0; i < $(checkBoxes).size();i++){
							if($(checkBoxes)[i].checked){
								var temp = $(checkBoxes)[i];
								languageName += $(temp).attr("_name");
								languageName += ", ";
								codeList += $(checkBoxes)[i].value;
								codeList += " ";
                                count++;
							}
                            else if($($(checkBoxes)[i]).attr("disabled")){
                                var count_1 = 0;
                                for(j=0;j<boxes.length;j++){
                                    if(boxes[j]==$(checkBoxes)[i].value)
                                        count_1++;
                                }
                                if(count_1==0){
                                    temp = $(checkBoxes)[i];
                                    languageName += $(temp).attr("_name");
                                    languageName += ", ";
                                    codeList += $(checkBoxes)[i].value;
                                    codeList += " ";
                                    count++;
                                }
                            }
						}
						languageName = languageName.substr(0, languageName.length-2);
                        if(count==0)
                            languageName = "[click here to edit]";
						el.prev("span").html(languageName);
						codeList = codeList.substr(0, codeList.length-1);
                        newCheckedBox = $(this);
						$(this).closest("div").attr("value", codeList);
                        $(el).val(codeList);
						Helper.AjaxUpdate(el, function(data){
							holder = el.closest("[_editable]");
							dynamic = holder.attr("_dynamicResource");
                            for(i=0;i<$("input[disabled]",el).size();i++){
                                if($($("input[disabled]",el)[i]).attr("checked"))
                                    $($("input[disabled]",el)[i]).removeAttr("checked");
                                else
                                    $($("input[disabled]",el)[i]).attr("checked","checked");
                            }
                             $("input",el).removeAttr("disabled");
                             var codeList2 = "";
                            var languageName = "";
                            var count = 0;
                             for(i = 0; i < $(checkBoxes).size();i++){
                                if($(checkBoxes)[i].checked){
                                    var temp = $(checkBoxes)[i];
                                    languageName += $(temp).attr("_name");
                                    languageName += ", ";
                                    codeList2 += $(checkBoxes)[i].value;
                                    codeList2 += " ";
                                    count++;
                                }
                             }
                             languageName = languageName.substr(0, languageName.length-2);
                            if(count==0)
                                languageName = "[click here to edit]";
                            el.prev("span").html(languageName);
                            codeList2 = codeList2.substr(0, codeList2.length-1);
                            newCheckedBox = $(this);
                            $(this).closest("div").attr("value", codeList2);
                            $(el).val(codeList2);
                            if(codeList2!=codeList)
                                Helper.AjaxUpdate(el, function(data){},function(){});
							el.prev("span").text($(":selected", el).attr("_display"));
						}, function(data){
                            // @todo to do later
                        });
					});
                    break;
                default: break;
            }

            el.attr("_binded", "1");
        },
        ApplyVisualStyles : function(){
        // @TODO make IE6 supports the css3 hover styles
        },
        Animate : function(el){
            el.css("cursor", "pointer").css("backgroundColor", "#ffffff").animate({
                "backgroundColor" : "#eaeaea"
            }, "slow", "linear", function(){
                $(this).animate({
                    "backgroundColor" : "#f9f9f9"
                }, "slow")
            });
        },
        MakeEditable : function(){

            if ($("#pageInfo").attr("_host") == "0" ) return false;
            field = $("[_editable]");
            if (field.attr("_init")) return false;
            holder = field.closest("[_editableHolder]").attr("_updating", 0);
            holder.hover(function(){
                Helper.Animate($(this));
            }, function(){
                $(this).stop().css("backgroundColor", "#ffffff");
            })
            .click(function(evt){

                if ($(this).attr("_updating") == 1) return false; // do not allow editing while submitting
                // create editable area
                localField = $(this).children("[_editable]");
                inputField = null;

                if (localField.attr("_editType") == "text"){

                    // This is the INPUT TYPE="TEXT" wrapper
                    // Create a input field when ever the elemented is clicked


                    localField.attr("_currentValue", localField.text());
                    inputField = $("<input type='text' />")
                    .attr("_field", localField.attr("_field"))
                    .attr("_controller", localField.attr("_controller"))
                    .addClass(localField.attr("_editCss")).val(localField.text())
                    .appendTo(localField.empty()).focus().select();
					if(localField.closest("tr").attr("_tabindex")=="6"){
                        inputField.css("width","100px");
                        if(inputField.val()=="[click here to edit]")
                            inputField.val("");
                        else{
                            inputField.val(localField.attr("_currentValue").substr(0,localField.attr("_currentValue").length-2));
                        }
                        $("tr[_tabindex=6] td").append("cm");
                    }
                    if(inputField.val()=="[click here to edit]"||inputField.val()=="[How are you feeling today?]")
                        inputField.val("");
                    Helper.AjaxUpdateInit(inputField, Helper.AJAX_TYPE_TEXT);

                } else if (localField.attr("_editType") == "textarea"){
                    // This is the TEXTAREA wrapper
                    localField.attr("_currentValue", localField.html());
                    inputField = $("<textarea />")
                    .attr("_field", localField.attr("_field"))
                    .attr("_controller", localField.attr("_controller"))
                    .addClass(localField.attr("_editCss")).val(localField.html().replace(/<BR>/g, '\n').replace(/<br>/g, '\n').replace(/&lt;/g, '<').replace(/&gt;/g, '>'))
                    .appendTo(localField.empty()).focus().select();
                    if($.trim(inputField.val())==$.trim("[click here to edit]")){
                        localField.attr("_currentValue","");
                        inputField.val("");
                    }
                    Helper.AjaxUpdateInit(inputField, Helper.AJAX_TYPE_TEXTAREA);


                } else if (localField.attr("_editType") == "select"){
                    // Select Box wrapper

                    // The display field
                    displayField = $("span", localField).hide();
                    // The select box
                    inputField = $("select", localField).show()
                        .attr("_field", localField.attr("_field"))
                        .attr("_controller", localField.attr("_controller"))
                        .focus();

                    Helper.AjaxUpdateInit(inputField, Helper.AJAX_TYPE_SELECT);
                } else if (localField.attr("_editType") == "checkBox"){
                    // Check Box wrapper
					displayField = $("span:first", localField).hide();
					inputField = $("div.checkBoxSelection",localField).show()
						.attr("_field", localField.attr("_field"))
						.attr("_controller", localField.attr("_controller"));
						//.focus();
                    Helper.AjaxUpdateInit(inputField, Helper.AJAX_TYPE_CHECKBOX);
                }else if (localField.attr("_editType") == "date"){
                    // Date picking object
                    // Append an input which will initialize a datepicker from jQuery UI
                    localField.attr("_currentValue", localField.text());
                    if(localField.text().indexOf("-")!=-1)
                        dobString = $.trim(localField.attr("_currentValue"));
                    else{
                        d = new Date();
                        dobString = d.getFullYear()+"-"+d.getMonth()+"-"+d.getDay();
                    }
                    dobParts = dobString.split("-");
                    dob = new Date();
                    dob.setFullYear(dobParts[0], dobParts[1]-1, dobParts[2]);

                    inputField = $("<input type='text' _firing='0' />")
                    .val(localField.text())
                    .datepicker({
                            // dateFormat : "dd MM yy",
                            changeMonth: true,
                            changeYear: true,
                            defaultDate : dob,
                            dateFormat : "yy-mm-dd",
                            maxDate : '0',
                            minDate : '-100y',
                            yearRange : '-100:+100',
                            // defaultDate : localField.attr("_currentValue"), // localField.attr("_currentValue"), //"21 August 1981", //"1981-08-21",//$(this).val(),
                            showOn : 'focus',
                            // buttonImage : 'images/calendar.gif',
                            // buttonImageOnly : true,
                            showAnim : 'slideDown',
                            onSelect : function(date){
								$(inputField).removeAttr("disabled");
                                localField.attr("_currentValue", date);
                                inputField.trigger("fire");
                                $(this).attr("firing", 1);
                                // return false;
                            },
                            onClose : function(date){
                                if ($(this).attr("firing")!= 1){
                                    $(this).remove();
                                    localField.text(localField.attr("_currentValue"));
                                }
                                return false;
                            }
                        })
                        .attr("_field", localField.attr("_field"))
                        .attr("_controller", localField.attr("_controller"))
                        .addClass(localField.attr("_editCss"))//.val(localField.text())
                        .appendTo(localField.empty()).focus()
						.attr("disabled","disabled");
                    Helper.AjaxUpdateInit(inputField, Helper.AJAX_TYPE_DATE);
                }

                inputField.click(function(evt){
                    return false;
                });

            });
            field.attr("_init", 1);
        }
    }

    Helper.MakeEditable();
//    if ($("#widget-introduction").size() > 0){
//        leftHeight = $("div.widget-panel-small").height();
//        rightHeight = $("div.widget-panel-big").height();
//        diff = leftHeight - rightHeight;
//        if (diff > 0){
//            $("#widget-introduction div.content").height($("#widget-introduction div.content").height() + diff * 0.25);
//            $("#widget-profile div.content").height($("#widget-profile div.content").height() + diff * 0.75);
//        }
//    }

    $("input[type=text]").focus(function(){
        $(this).select();
    });

    // status text field
    if ($("div.subheader").size()>0){
        subheader = $("div.subheader");
    }

    if ($("#widget-picture").size() > 0){
		var Y = YUI();
    	Y.use('node','imageloader',function(Y){
    		var userPhoto = Y.one('#widget-picture div.user-photo img[_src]');
    		if(!userPhoto.get('id'))
    			userPhoto.set('id',Y.stamp(userPhoto));
    		var userPhotoGroup = new Y.ImgLoadGroup({ foldDistance:80});
    		userPhotoGroup.registerImage({domId: userPhoto.get('id'),srcUrl: userPhoto.getAttribute('_src')});
    		var photos = Y.all('#widget-picture div.photo-select div.container div.inner img.photo');
    		
    		var userPhotos = new Y.ImgLoadGroup({foldDistance:20});
    		photos.each(function(n,i){
    			if(!n.get('id'))
    				n.set('id',Y.stamp(n));
    			userPhotos.registerImage({domId: n.get('id'), srcUrl: n.getAttribute('_src')});
    		});
    	});
        wPic = $("#widget-picture");
        // initialize the scrolling pane
        var container = $(".container", wPic);
        var profilepic = $("div[_isprofilephoto=1]", container);
        profilepic.prependTo(profilepic.parent());
        var numOfPics = $("img", container).size();

        index = parseInt($("img", container).size());
        imgs = $("img:last", container);

        $(".inner", container).width(60*numOfPics);
        while($(".inner", container).height()>100) $(".inner", container).width($(".inner", container).width()+10);

        offset = $(".inner", container).parent().parent().width();
        var currentPhotoContainer = $("a[_class=currentPhoto] img", wPic);
        $("img", container).parent().parent().click(function(){

            $("div", container).removeClass("selected");
            $($(this)).addClass("selected");

            currentPhotoContainer.attr("src", $('a',this).attr("_zoom"));
            if ($("#pageInfo").attr("_host") == "1"){
                Popmenu.Attach($("img:first", $(this)));
            }
            $(this).blur();
            return false;
        });

        var cx = 0;
        container.mouseover(function(evt){
            cx = evt.clientX;
            scroller = setInterval(function(){
                containerCenter = container.offset().left + container.width()/2;
                // console.info(cx, containerCenter);
                offset = cx - containerCenter;
                // if ((offset > 60)||(offset < -60))
                    container.scrollLeft(container.scrollLeft()+ offset/40);
            }, 1);
        }).mousemove(function(evt){
            cx = evt.clientX;
        }).mouseout(function(evt){
            clearInterval(scroller);
        });

//        container.scrollLeft(0);
//
//        var scroller = null;
//        var speed = 2;
//        var maxspeed = 10;
//
//        $(".scroll.left", wPic).mouseover(function(){
//            scroller = setInterval(function(){
//                container.scrollLeft(container.scrollLeft()-speed);
//                if (speed > maxspeed) speed = maxspeed;
//                else speed *= 1.005;
//            }, 1);
//        }).mouseout(function(){ clearInterval(scroller); speed = 2 });
//
//        $(".scroll.right", wPic).mouseover(function(){
//            scroller = setInterval(function(){
//                container.scrollLeft(container.scrollLeft()+speed);
//                if (speed > maxspeed) speed = maxspeed;
//                else speed *= 1.005;
//            }, 1);
//        }).mouseout(function(){ clearInterval(scroller); speed = 2 });

        jQuery.easing.bounceout = function(p, n, firstNum, delta, duration) {
            if ((n/=duration) < (1/2.75)) {
                return delta*(7.5625*n*n) + firstNum;
            } else if (n < (2/2.75)) {
                return delta*(7.5625*(n-=(1.5/2.75))*n + .75) + firstNum;
            } else if (n < (2.5/2.75)) {
                return delta*(7.5625*(n-=(2.25/2.75))*n + .9375) + firstNum;
            } else {
                return delta*(7.5625*(n-=(2.625/2.75))*n + .984375) + firstNum;
            }
        };

        jQuery.easing.bouncein = function(x, t, b, c, d) {
            return c - jQuery.easing['bounceout'](x, d-t, 0, c, d) + b;
        };
//
//
//        $(".scroll.left", wPic).click(function(){
//            container.animate({
//                scrollLeft: "-=" + offset
//            }, 500, "bounceout");
//        });
//
//        $(".scroll.right", wPic).click(function(){
//            container.animate({
//                scrollLeft: "+=" + offset
//            }, 500, "bounceout");
//        });
    }

    if ($("#widget-emoticon").size() > 0){
        wEmo = $("#widget-emoticon");
        icons = $("img.emoticon", wEmo).click(function(evt){
            // console.info(evt, evt.clientX, evt.clientY);
            return false;
        });
    }
	var updateTime = {
        update: function(){
            var currentTime = new Date();
            $.each($("div.entry[_time]","#widget-events"),function(idx, obj){
                var entryDay = (($(obj).attr("_time").split("-")[2].split(" "))[0]);
                var entryMonth = $(obj).attr("_time").split("-")[1];
                var entryYear = $(obj).attr("_time").split("-")[0];
                if(entryYear==currentTime.getFullYear()){
                    if(entryMonth==currentTime.getMonth()+1){
                        if(entryDay==currentTime.getDate()){
                            if($("p.today").size()==0)
                                $(obj).before("<div class=\"seperator\"></div><p class=\"header today\">today</p>");
                        }
                        else if(entryDay==currentTime.getDate()-1){
                            if($("p.yesterday").size()==0)
                                $(obj).before("<div class=\"seperator\"></div><p class=\"header yesterday\">yesterday</p>");
                        }
                        else{
                            if($("p.older").size()==0)
                                $(obj).before("<div class=\"seperator\"></div><p class=\"header older\">older</p>");
                        }
                    }
                    else{
                        if($("p.older").size()==0)
                            $(obj).before("<div class=\"seperator\"></div><p class=\"header older\">Older</p>");
                    }
                }
                else{
                    if($("p.older").size()==0)
                        $(obj).before("<div class=\"seperator\"></div><p class=\"header older\">Older</p>");
                }
            });
        }
    };
    if ($("#widget-events").size() > 0){
		//updateTime.update();		
        times = 0;
        wEvt = $("#widget-events");
        // Hide and show title buttons
        firstRows = $("tr:first", $("table.entry-table", wEvt)).css("backgroundColor", "transparent").hover(function(){
            $(this).css("opacity", 1).stop().animate({
                // opacity: 1,
                }, 500).css("backgroundColor", "#efefef");
            $("a", $(this)).show();
        }, function(){
            $(this).stop().animate({
                // opacity: 1
                }, 500).css("backgroundColor", "transparent");
            $("a.thread-link", $(this)).hide();
        })
        if($("div.system_message").size()>0){
            $("#sendMail",".system_message","wEvt").click(function(){
                $(this).css("color","grey");
                $.post("index.php?r=user/resendMail",{user_id:$(this).closest("tr").attr("_userid")},function(data){$(".system_message table.thread-table tbody","#widget-events").append("<tr><td></td><td>Email has been sent,  please check!</td></tr>");$("#sendMail",".system_message","wEvt").css("color","blue");});
            });
        }
        else{
            // History toggle
            $("a[_class=toggleHistory]", firstRows).click(function(){
                if($("[_tag=replies]", $(this).closest("table.entry-table")).css("display")=="none")
                    $("[_tag=replies]", $(this).closest("table.entry-table")).show();
                else
                    $("[_tag=replies]", $(this).closest("table.entry-table")).hide();
                //$("[_tag=replies]", $(this).closest("table.entry-table")).toggle();
                return false;
            });

            // Reponse fields
            $("a[_class=reply]", firstRows).click(function(){
                field = $("tr.reply", $(this).closest("table.entry-table")).show();
                reply = $("input", field).focus().select();
                // add events for the input field
                if (reply.attr("_init") == undefined ){
                    reply.attr("_init", true);

                    reply.blur(function(){
                        reply.closest("tr").hide();
                    });

                    reply.keydown(function(evt){
                        switch(evt.keyCode){
                            case 9: // Tab
                                return false;
                            case 13: // Enter
                                $.ajax({
                                    url : 'index.php?r=userMessage/sendMessage',
                                    type : 'post',
                                    data : {
                                        //user_id : reply.user_id,
                                        messageIdFrom : reply.closest(".entry-table").attr("_eventid"),
                                        user_id : reply.closest(".entry-table").attr("_messageFrom"),
                                        message : reply.val(),
                                        object_id : 0,
                                        type : 1
                                    },
                                    beforeSend : function(){
                                        // console.info(reply);
                                    },
                                    success : function(){
                                        EventLog.Info("Reply has been sent.");
                                    }
                                });
                                // entry = $("table.thread-table tr:first", $(this).closest("tr").next("tr"));
                                // newentry = entry.clone().insertBefore(entry).hide().fadeIn();
                                $(this).trigger("blur");
                                break;
                            case 27: // Esc
                                $(this).trigger("blur");
                                break;
                            default: // Nothing to do
                                break;
                        }
                    })
                }
                return false;
            });

            $("span.user", wEvt).click(function(){
                window.location.href = "index.php?r=user/show&id=" + $(this).attr("_userid");
            });
			
			var temp;
            $(".thread-picture[_src]").hover(
                function(){
                    temp = $(this).attr("src");
                    $(this).attr("src",$(this).attr("_src"));
                    $(this).attr("_src",temp);
                },
                function(){
                    temp = $(this).attr("src");
                    $(this).attr("src",$(this).attr("_src"));
                    $(this).attr("_src",temp);
                });
            $($("input", ($(".filters"), wEvt))[0]).click(function(){ // Message filter
                $("[_eventType=message]").parent()
                .add($("[_eventType=a]").parent())
				.add($("[_eventType=1]").parent())
                .toggle();
            });
			
            $($("input", ($(".filters"), wEvt))[0]).click(function(){ // Message filter
                $("[_eventType=message]").parent().toggle();
            });

            $($("input", ($(".filters"), wEvt))[1]).click(function(){ // Events
                $("[_eventType=d]").parent()
                .add($("[_eventType=g]").parent())
                .add($("[_eventType=h]").parent())
                .add($("[_eventType=i]").parent())
                .add($("[_eventType=j]").parent())
                .add($("[_eventType=k]").parent())
                .add($("[_eventType=l]").parent())
                .toggle();
            });

            $($("input", ($(".filters"), wEvt))[2]).click(function(){ // Friend List
                $("[_eventType=e]").parent()
                .add($("[_eventType=f]").parent())
                .toggle();
            });

            $($("input", ($(".filters"), wEvt))[3]).click(function(){ // Comments
                $("[_eventType=b]").parent()
                .add($("[_eventType=c]").parent())
				.add($("[_eventType=2]").parent())
                .add($("[_eventType=3]").parent())
				.add($("[_eventType=5]").parent())
                .add($("[_eventType=6]").parent())
                .add($("[_eventType=7]").parent())
                .toggle();
            });
        }
		$("a.listMoreEntry").click(function(){
            //alert($("div.entry:last").attr("_time"));
            $.post("index.php?r=homePage/listMoreEntry",{time:$("div.entry:last").attr("_time"),times:times++},function(data){$("div.entry:last","div#widget-events").after(data);});
        });
    }

    // Searching
    if ($("#widget-search-settings").size() > 0){
        wSS = $("#widget-search-settings");
        $("#SearchForm_country_code").change(function(){
            cc = $(this).attr("value");
            placeHolder = $("#SearchForm_state_code").parent();
            $.get("index.php?r=user/getStateSelect", {
                "country_code" : cc
            }, function(data){
                placeHolder.empty();
                $(data).appendTo(placeHolder);
            });
        });
		
		$("img.country-flag[_country]").css("cursor", "pointer").click(function(){
            $("option[selected]", $("select.country-select")).removeAttr("selected");
            $("option[value="+ $(this).attr("_country") +"]").attr("selected", "selected");
            $("select.country-select").closest("form").submit();
            return false;
        });
		
		// switch views
        $("a[_tag=photo_view]").click(function(){
            $.cookie('view', 'photo', {
                expires: 7
            });
            window.location.reload();
//            curl = window.location.href;
//            if (curl.indexOf("&view=photo") != -1){
//                return false;
//            } else if (curl.indexOf("&view=list") != -1) {
//                window.location.href = curl.replace("&view=list", "&view=photo");
//            } else window.location.href = curl + "&view=photo";
//            return false;
        });

        $("a[_tag=list_view]").click(function(){
            $.cookie('view', 'list', {
                expires: 7
            });
            window.location.reload();
//            curl = window.location.href;
//            if (curl.indexOf("&view=list") != -1){
//                return false;
//            } else if (curl.indexOf("&view=photo") != -1) {
//                window.location.href = curl.replace("&view=photo", "&view=list");
//            } else window.location.href = curl + "&view=list";
//            return false;
        });
    }

	if($("#widget-ibuddy").size() > 0){
		var Y = YUI();
    	Y.use('node','imageloader',function(Y){
    		var products = Y.all('#widget-ibuddy div.regMore img[_src]');
    		var productsPhoto = new Y.ImgLoadGroup({ name: 'group 1', timeLimit: 0.1 });
    		products.each(function(n,i){
    			n.set('id',Y.stamp(n));
    			productsPhoto.registerImage({ domId: n.get('id'), srcUrl: n.getAttribute('_src') });
    		});
    	});
        $(".serial-number").keyup(function(){
            if($(this).val().length==4){
                var a = $(this).closest("td").next("td");
                $("input.serial-number",a).focus();
            }
        });
        if($("div.ibuddy-select img","#widget-ibuddy").size()==0)
            $("div.regMore","div.content","#widget-ibuddy").show();
        else
             $("div.regMore","div.content","#widget-ibuddy").hide();
        $("a#regMore","#widget-ibuddy").click(function(){
           $("div.regMore","div.content","#widget-ibuddy").show();
           $($("div.content","#widget-ibuddy")[1]).hide();
           $(this).hide();

        });

		$("input#back","#widget-ibuddy").click(function(){
            $("div.content","#widget-ibuddy").show();
            $(this).closest("div.regMore").hide();
            $(".incorrect","#widget-ibuddy").hide();
            $("table[_seriesid]","div.regMore","#widget-ibuddy").hide();
            $("table[_seriesid]:first","div.regMore","#widget-ibuddy").show();
            $("a#regMore","#widget-ibuddy").show();
            $(".serial-number").val("");
		});
        $(".seriesHeader","#widget-ibuddy").hover(function(){
                Helper.Animate($(this));
        }, function(){
            $(this).stop().css("background", "#ffffff");
        });
        $(".seriesHeader","#widget-ibuddy").click(function(){
            var temp = $(this).attr("_seriesid");
            $("table[_seriesid]","div.regMore","#widget-ibuddy").hide();
            $("table[_seriesid="+temp+"]","div.regMore","#widget-ibuddy").show();
        });
        $("table[_seriesid]","div.regMore","#widget-ibuddy").hide();
        $("table[_seriesid]:first","div.regMore","#widget-ibuddy").show();
        $("#register_submit").hide();

        $("#submit","#widget-ibuddy").click(function(){
            if($("#reloadFields").css("display")=="none"){
				$("#reloadFields").show("slow");
				$("#register_submit").show("slow");
				$("input#back").show("slow");
                $("#submit","#widget-ibuddy").val("Submit");
            }
            else{
                var serial = "";
                var model = $("input[type=radio]:checked").val();
                var user = $("#reloadFields").attr("_user_id");
                for(i = 0;i<4;i++){
                    var a = $(".serial-number")[i];
                    serial += $(a).val().toUpperCase();
                    if(i!=3)
                        serial += "-";
                }
                $.ajax({
                    url : "index.php?r=user/ibuddyRegistration",
                    type : "post",
                    data : {
                        serial : serial,
                        model : model,
                        user : user
                    },
                    beforeSend : function(){
                        $("input").attr("disabled","disabled");
                    },
                    success : function(data){
                        if(data==0){
                            window.location = "index.php?r=user/show";
                        }else if(data==1){
                            $(".incorrect","#widget-ibuddy").hide();
                            $(".registered","#widget-ibuddy").show();
                        }
                        else{
                            $(".registered","#widget-ibuddy").hide();
                            $(".incorrect","#widget-ibuddy").show();
                        }
                        $("input").removeAttr("disabled")
                    },
                    error : function(xhr){
                        console.info(xhr.status);
                        $("input").removeAttr("disabled");
                        if (callback_failed) callback_failed();
                    }
                });
            }
        });
        /*******************************************************************/
        iwPic = $("#widget-ibuddy");
        var first = $(".ibuddy-select img:first","#widget-ibuddy").attr("_productid");
        var inumOfPics = $("img",(".photo-select","#widget-ibuddy")).closest("a[_productid="+first+"]").size();
        $.each($(".container a","#widget-ibuddy"),function(idx, obj){
            if($(obj).attr("_productid")!=first){
                $("img",obj).hide();
            }else{
                $("img",obj).show();
                if($(obj).attr("_isProfile")==1)
                        $('img',obj).addClass("selected");
            }
        });
        if($(".container a[_productid="+first+"]","#widget-ibuddy").size()==0){
            $(".ibuddy-photo img","#widget-ibuddy").attr("src",$(".ibuddy-select img[_productid="+first+"]","#widget-ibuddy").attr("_src"));
            $("div.photo-select","#widget-ibuddy").hide();
            $("#ibuddy-comment","#widget-ibuddy").hide();
        }
        $("img[_productid]", iwPic).click(function(data){
            var productid = $(this).attr("_productid");
            inumOfPics = $("img",(".photo-select","#widget-ibuddy")).closest("a[_productid="+productid+"]").size();
            $(".inner", icontainer).width(70*inumOfPics);
            if($(".container a[_productid="+productid+"]","#widget-ibuddy").size()==0){
                $("#ibuddy-comment","#widget-ibuddy").hide();
                $("div.tips","#widget-ibuddy").show();
                $("div.photo-select","#widget-ibuddy").hide();
                $(".ibuddy-photo img","#widget-ibuddy").attr("src",$(".ibuddy-select img[_productid="+productid+"]","#widget-ibuddy").attr("_src"));
            }
            else{
                $("div.tips","#widget-ibuddy").hide();
                $("div.photo-select","#widget-ibuddy").show();
                $("#ibuddy-comment","#widget-ibuddy").show();
            }
            count=0;
            $.each($(".container a","#widget-ibuddy"),function(idx, obj){
                $('img',obj).removeClass("selected");
                if($(obj).attr("_productid")!=productid){
                    $("img",obj).hide();
                }else{
                    if($(obj).attr("_isProfile")==1&&count==0){
                        count++;
                        $('img',obj).addClass("selected");
                        $(".comment","#widget-ibuddy").attr("_object_id",$(obj).attr("_productPhotoId"));
                        $(".ibuddy-photo img","#widget-ibuddy").attr("src",$(obj).attr("_zoom"));
                    }
                    $("img",obj).show();
                }
            });
            $("#uploaderOverlay2","#widget-ibuddy").attr("_productid",productid);
            $(".container", iwPic).scrollLeft(0);
        });
        // initialize the scrolling pane
        var icontainer = $(".container", iwPic);
        $(".inner", icontainer).width(70*inumOfPics);
        index = parseInt($("img", icontainer).size());
        imgs = $("img:last", icontainer);

        offset = $(".inner", icontainer).parent().width();
        var icurrentPhotoContainer = $("a[_class=currentPhoto] img", iwPic);
        $("img", icontainer).parent().click(function(){
            $("img", icontainer).removeClass("selected");
            $("img", $(this)).addClass("selected");
            icurrentPhotoContainer.attr("src", $(this).attr("_zoom"));
            $(".comment","#widget-ibuddy").attr("_object_id",$(this).attr("_productPhotoId"));
            if ($("#pageInfo").attr("_host") == "1"){
                Popmenu.Attach($("img:first", $(this)));
            }
            $(this).blur();
            return false;
        });
        icontainer.mouseover(function(evt){
            cx = evt.clientX;
            scroller = setInterval(function(){
                containerCenter = icontainer.offset().left + icontainer.width()/2;
                // console.info(cx, containerCenter);
                offset = cx - containerCenter;
                // if ((offset > 60)||(offset < -60))
                    icontainer.scrollLeft(icontainer.scrollLeft()+ offset/40);
            }, 1);
        }).mousemove(function(evt){
            cx = evt.clientX;
        }).mouseout(function(evt){
            clearInterval(scroller);
        });
	}

    // Status Text
    if ($("p.status-text[_tag=edit]").size()>0){
        line = $("p.status-text[_tag=edit]").prev();
        warpline = $("p.status-text[_tag=edit]");
        line.css("cursor", "pointer").hover(function(){
            $(this).css("background", "#eaeaea");
        }
        , function(){
            $(this).css("background", "#ffffff");
        }).click(function(){
            line.hide();
            warpline.show();
            $("input", warpline).focus().select().keydown(Profile.handleKey).blur(Profile.cancel);
        });
    }

    if ($("#widget-profile").size() > 0){
		if($("tr[_tabindex=6]").children("td").text()!="[click here to edit]")
            $("tr[_tabindex=6]").children("td").text($("tr[_tabindex=6]").children("td").text()+"cm");
        $("body").click(function(evt){
            var holder = $(evt.target).closest("tr");
            var editType = $(holder).attr("_editType");
            if(editType!="checkBox"){
                $("table.profile div.checkBoxSelection",".content").hide().prev("span").show();
            }
            else{
                $.each($("table.profile div.checkBoxSelection",".content").closest("tr"), function(idx, obj){
                    if($(obj).attr("_tabIndex")!=$(evt.target).closest("tr").attr("_tabIndex")){
                        $("div.checkBoxSelection",obj).hide().prev("span").show();
                    }
                });
            }
        });
        wProfile = $("#widget-profile");
        host = false;
        if (wProfile.attr("_host") == "1"){
            // right granted to update
            host = true;
            $("tr.edit-row-inactive", wProfile).prev("tr").hover(function(){
                $(this).addClass("edit-row-active");
            }, function(){
                $(this).removeClass("edit-row-active");
            }).children("td").click(function(){
                input = $("input", $(this).parent("tr").hide().next("tr").show()).focus().select();
                if (input.size()>0 && !input.attr("_init")){
                    if (input.attr("type") == "text"){
                        // text input
                        input.attr("_currentValue", input.val());
                        input.keydown(Profile.handleKey);
                        input.blur(Profile.cancel);
                        input.attr("_init", "1");
                    }
                } //else {
				else if(select.size()>0 && !select.attr("_init")){
                    select = $("select", $(this).parent("tr").hide().next("tr").show()).focus();
                    //if (select.size()>0 && !select.attr("_init")){
                        // selection
                        select.attr("_currentValue", select.val());
                        //select.change(Profile.update($(this), "gender", select.val()));
                        select.change(function(){
                            Profile.updateSelect($(this), "gender", $(this).val(), gender = $(this).val() == 'M'? "Male" : ($(this).val() == ' F'? "Female" : "Unspecified"));
                            $(this).unbind("change");
                        });
                        select.blur(function(){
                            $(this).closest("tr").hide().prev("tr").show();
                        });
                    //}
                }else if(form.size()>0 && !form.attr("_init")){
					form = $("form", $(this).parent("tr").hide().next("tr").show()).focus();
					form.attr("_currentValue", select.val());
					form.blur(function(){
						$(this).closest("tr").hide().prev("tr").show();
					});
				}else{
					//console.info("hihi");//do later
				}

            });
        }
    }
    if ($("#widget-search-result").size() > 0){
        wSR = $("#widget-search-result");
        $("img.user-link", $("div.entry[_userid]")).css("cursor", "pointer").click(function(){
            window.location.href = "/index.php?r=user/show&id=" + $(this).closest("div.entry").attr("_userid");
        });
		
		btnDiv = $("div.button-pane", wSR);
        $("li", btnDiv).hover(function(){
            $(this).addClass("ui-state-focus");
        }, function(){
            $(this).removeClass("ui-state-focus");
        });

        $("li.view-profile").click(function(){
            window.location.href = "/index.php?r=user/show&id=" + $(this).closest("div.entry[_userid]").attr("_userid");
        });
    }
    if($("#widget-register").size()>0){
        $("[_uncheckme]").removeAttr("checked").parent().prev().children("input").attr("checked", "checked");
        $(".serial-number").keyup(function(){
            if($(this).val().length==4){
                $(this).next("input.serial-number").focus();
            }
        });
        var a = new Date();
        $("#RegistrationForm_timezone").val(a.getTimezoneOffset()/60*(-1));
        $("#RegistrationForm_timezone").attr("value",a.getTimezoneOffset()/60*(-1));
//        if ($("input[name='RegistrationForm[hasIBuddy]']:checked").val()==0)
//            $("#ibuddyRegistration").add($("#ibuddyRegistration").next()).show();
//        else
//            $("#ibuddyRegistration").add($("#ibuddyRegistration").next()).hide();
        $("input[name='RegistrationForm[hasIBuddy]']").click(function(){
            if ($("input[name='RegistrationForm[hasIBuddy]']:checked").val()==0)
                $("#ibuddyRegistration").add($("#ibuddyRegistration").next()).show();
            else
                $("#ibuddyRegistration").add($("#ibuddyRegistration").next()).hide();
            $(this).blur();
        });
        if($("option",".state","#widget-register").size()==1)
            $("option",".state","#widget-register").closest("tr").hide();
        else
            $("option",".state","#widget-register").closest("tr").css("display","");

        $("#RegistrationForm_country_code").change(function(){
            cc = $(this).attr("value");
            placeHolder = $("#RegistrationForm_state_code").parent();
			//$("<tr><th>State</th><td id=\"here\"></td></tr>").insertAfter($("#RegistrationForm_country_code").closest("tr/"));
            $.get("index.php?r=user/getStateSelect", {
                "country_code" : cc,
                "form" : "register"
            }, function(data){
                placeHolder.empty();
                $(data).appendTo(placeHolder);
                if($("option",".state","#widget-register").size()==1)
                    $("option",".state","#widget-register").closest("tr").hide();
                else
                    $("option",".state","#widget-register").closest("tr").css("display","");
            });
			if($('option').length>60)
				$('#stateDropList').show("slow");
        });
    }

    // Comment Fields
    $("[_tag=comment][_type]").focus(function(){
        $(this).css("fontStyle", "normal").css("color", "#666666");
        $(this).attr("value","");
        // div.widget-panel-big input.comment:focus { font-style: normal; color:#666666 }
    }).blur(function(){
        $(this).css("fontStyle", "italic").css("color", "#999999");
        $(this).attr("value","leave a comment…");
    }).keydown(function(evt){
        temp = $(this);
        switch (evt.keyCode){
            case 9 : return false; break;
            case 13 : // send comment
                $.ajax({
                    url : "index.php?r=userMessage/sendMessage",
                    type : "post",
                    data : {
                        user_id : $("#pageInfo").attr("_userid"),
                        type : $(this).attr("_type"),
                        object_id : ($(this).attr("_object_id") == undefined)? 0 : $(this).attr("_object_id"),
                        message : $(this).val()
                    },
                    timeout : 5000,
                    beforeSend : function(){
                        EventLog.Info("Sending...");
                        $(temp).attr("disabled","disabled");
                        // alert('!');
                    },
                    success : function(data){
                        $(temp).attr("value","leave a comment…");
                        $(temp).removeAttr("disabled");
                        $(temp).blur();
                        // alert("Comment sent");
                        if (data == "1"){
                            // alert("Comment sent");
                            EventLog.Info("Your comment has been sent.");
                        } else if(data == "0") {
                            // alert("Action failed");
                            EventLog.Error("Cannot send comment. Please try again.");
                        }
                    },
                    error : function(data){
                        console.info(data);
                        EventLog.Error("Cannot send comment. Please try again.");
                    },
                    complete : function(xhr, text){
                        $(temp).removeAttr("disabled");
                        // console.info(xhr, text);
                    }
                });
                break;
            case 27 : $(this).blur(); break;
            default : break;
        }
    });

    // Special Buttons
    if ($("#pageInfo")){ // only available on page with user info
        $("[_tag=addFavourite]").click(function(){
            if($("div#widget-search-result[_userid]").size()>0){
                // add to favourite list
                //            $.ajax({
                //                url : "index.php?r=user/addFavourite",
                //                type : "post",
                //                data : {
                //                    user_id : $("#pageInfo").attr("_userid")
                //                },
                //                success : function(data){
                //                    if (data == "1"){
                //                        alert("User successfully added");
                //                    } else if(data == "0") {
                //                        alert("Action failed");
                //                    }
                //                }
                //            });
                Popmenu.Attach($(this));
                return false;
            }
            else
                window.location.href = "index.php?r=site/login";
        });

        $("[_tag=sendMessage]").click(function(){
            messagebox = $("input.message-text-edit", $(this).closest(".subheader"));
            messagebox.next("p").show();
            messagebox.show().focus().val($(this).attr("_defaultValue"));
            if (messagebox.attr("_init") != 1){
                messagebox.keydown(function(evt){
                    switch(evt.keyCode){
                        case 9: return false; break;
                        case 13: {
                            $.ajax({
                                url : "index.php?r=userMessage/sendMessage",
                                type : "post",
                                data : {
                                    user_id : $("#pageInfo").attr("_userid"),
                                    type : $(this).attr("_type"),
                                    message : $(this).val(),
                                    object_id : 0
                                },
                                beforeSend : function(){
                                    messagebox.next("p").hide();
                                    EventLog.Info("Sending...");
                                },
                                success : function(data){
                                    if (data == "1"){
                                        EventLog.Info("Message has been sent");
                                    } else if(data == "0") {
                                        EventLog.Error("Cannot send comment. Please try again.");
                                    }
                                },
                                error : function(){
                                    // console.error("!!!");
                                }
                            });
                        }
                        case 27: $(this).blur(); break;
                    }
                }).blur(function(){
                    messagebox.next("p").hide();
                    $(this).hide();
                });
                messagebox.attr("_init", 1);
            }
            return false;
            }
        );
    }
    if ($("#widget-user-settings").size() > 0){
        if($("option","#SettingsForm_state_code").size()>1)
            $("#SettingsForm_state_code").closest("tr").css("display", "");
        else
            $("#SettingsForm_state_code").closest("tr").hide("");

       $("tr.changePassword","#widget-user-settings").hide("");
        $.each($("tr.changePassword input","#widget-user-settings"), function(idx, obj){
            if($(obj).val().length!=0){
                $("div#change","#widget-user-settings").closest("tr").hide();
                $("tr.changePassword","#widget-user-settings").css("display","");
                $("tr.change","#widget-user-settings").closest("tr").hide();
            }
        });
       $("div#change","#widget-user-settings").click(function(){
           $(this).closest("tr").hide();
           $("tr.changePassword","#widget-user-settings").css("display","");
       });
       $("#SettingsForm_country_code").change(function(){
            cc = $(this).attr("value");
            placeHolder = $("#SettingsForm_state_code").parent();
            $.get("index.php?r=user/getStateSelect", {
                "country_code" : cc,
                "form"  : "settings"
            }, function(data){
                placeHolder.empty();
                $(data).appendTo(placeHolder);
                if($("option","#SettingsForm_state_code").size()>1)
                    $("#SettingsForm_state_code").closest("tr").css("display", "");
                else
                    $("#SettingsForm_state_code").closest("tr").hide("slow");
            });
        });
    }
    $("#forgetPassword").click(function(){

        $("#lostpassword-dialog").dialog({
            title : "Forget password?",
            modal : true,
            resizable : false,
            width: 400,
            open : function(){
                $("input:text", $(this)).removeAttr("disabled");
            },
            buttons : {

                'Cancel' : function(){
                    $(this).dialog('destroy');
                },

                'Ok' : function(){
                    var email = $("input:text", $(this)).val();
                    var emailField = $("input:text", $(this));
                    if (email.length > 0){
                        var self;
                        $.ajax({
                            type : 'post',
                            url : "index.php?r=user/forgetPassword",
                            dataType : 'text',
                            data : {
                                email : email
                            },
                            beforeSend : function(){
                                emailField.attr("disabled", "disabled");
                                $(this).dialog('disable');
                            },
                            error : function(xhr){},
                            success : function(data){
                                $(this).dialog('enable');
                                $("#lostpassword-dialog").dialog('destroy');
                                if (data == '1'){
                                    $("<div />").text("Email has been sent,  please check your mail box now.").dialog({
                                        modal : true,
                                        resizable : false,
                                        title : "Email Sent",
                                        buttons : {
                                            'Ok' : function(){ $(this).dialog('destroy')}
                                        }
                                    });
                                } else {
                                    $("<div />").text("Email not found. Please try again.").dialog({
                                        modal : true,
                                        resizable : false,
                                        title : "Error",
                                        buttons : {
                                            'Ok' : function(){ $(this).dialog('destroy')}
                                        }
                                    });
                                }
                            }
                        });
                        // $.post("index.php?r=unc_user/resetPassword",{email: email},function(data){alert(data)});
                    }
                    // console.info(email);
                    // $.post("index.php?r=unc_user/resetPassword",{email: email},function(data){alert(data)});
                }
            }
        });

    });
    if($('#widget-activate').size()>0){
        setTimeout('window.location="index.php?r=homePage/listMyHome"',5000);
    }
    if($('#widget-login').size()>0){
        $('#regNow','#widget-login').click(function(){
            window.location = "index.php?r=user/register";
        });
    }

    // forgetpassword redirect from old site
    if (window.location.href.match(/#forgetpassword/)){
        $("#forgetPassword").click();
    }
    if($("#widget-emoticonList").size()>0){
        $("span.user", "#widget-emoticonList").click(function(){
                window.location.href = "index.php?r=user/show&id=" + $(this).attr("_userid");
        });
		$("img.user", "#widget-emoticonList").click(function(){
                window.location.href = "index.php?r=user/show&id=" + $(this).attr("_userid");
        });
        temp;
        $(".emoticon").click(function(){ Popmenu.Attach($(this));});
        $(".emoticon").hover(
            function(){
                $(this).css("border"," 1px solid #40a8eb");
                temp = $(this).attr("src");
                $(this).attr("src",$(this).attr("_src"));
                $(this).attr("_src",temp);
            },
            function(){
                $(this).css("border"," 1px solid #ffffff");
                temp = $(this).attr("src");
                $(this).attr("src",$(this).attr("_src"));
                $(this).attr("_src",temp);
            }
        );
		$(".emoticon","#widget-emoticonList").css("border"," 1px solid #ffffff");
        $("#back","#widget-emoticonList").click(function(){
            window.location.href = "index.php?r=emoticon/list";
        });
    }
	if ($("div.addon-listing").size() > 0){
        $("input[type=submit]","div.add-comment").click(function(){
            if($.trim($(this).prev().prev().val()).length>0){
                if($("table.addon_thread_table:last").size()>0){
                    $.ajax({
                        url : 'index.php?r=userMessage/sendMessage',
                        type : 'post',
                        data : {
                            //user_id : reply.user_id,
                            messageIdFrom : $("table.addon_thread_table:last").attr("_messageid"),
                            user_id : $(this).closest("div").attr("_userid"),
                            message : $(this).prev().prev().val(),
                            object_id : $(this).closest("div").attr("_addonid"),
                            type : 8
                        },
                        beforeSend : function(){
                            // console.info(reply);
                            if (typeof pageTracker != "undefined"){
                                pageTracker._trackPageview('/event/sendMessage');
                            }
                            $("input[type=submit]","div.add-comment").attr("disabled","disabled");
                            $("input[type=submit]","div.add-comment").prev().prev().attr("disabled","disabled");
                        },
                        success : function(){
                            EventLog.Info("Your comment has been sent.");
                            window.location.reload();
                            $("input[type=submit]","div.add-comment").removeAttr("disabled");
                            $("input[type=submit]","div.add-comment").prev().prev().removeAttr("disabled");
                        }
                    });
                }
                else{
                    $.ajax({
                        url : 'index.php?r=userMessage/sendMessage',
                        type : 'post',
                        data : {
                            user_id : $(this).closest("div").attr("_userid"),
                            message : $(this).prev().prev().val(),
                            object_id : $(this).closest("div").attr("_addonid"),
                            type : 8
                        },
                        beforeSend : function(){
                            // console.info(reply);
                            if (typeof pageTracker != "undefined"){
                                pageTracker._trackPageview('/event/sendMessage');
                            }
                            $("input[type=submit]","div.add-comment").attr("disabled","disabled");
                            $("input[type=submit]","div.add-comment").prev().prev().attr("disabled","disabled");
                        },
                        success : function(){
                            EventLog.Info("Your comment has been sent.");
                            window.location.reload();
                            $("input[type=submit]","div.add-comment").removeAttr("disabled");
                            $("input[type=submit]","div.add-comment").prev().prev().removeAttr("disabled");
                        }
                    });
                }
            }
            else{
                EventLog.Error("Blank comment cannot be sent");
            }
        });
        $("button.download", $("div.addon-listing")).add($("button.detail", $("div.addon-listing"))).hover(function(){
            $(this).addClass("ui-state-focus");
        }, function(){
            $(this).removeClass("ui-state-focus");
        }).css("cursor", "pointer");

        $("button.download", $("div.addon-listing")).click(function(){
            Downloader.Download($(this).attr("_src"), "add-on");// download files
			return false;
        });

        $("button.detail", $("div.addon-listing")).click(function(){
            window.location.href = $(this).closest("a").attr("href");// download files
        });
		$("button.more_infor", $("div#widget-addon-developer")).click(function(){
            window.location.href = $(this).closest("a").attr("href");// download files
        });
		$("img.user[_userid]").click(function(){
            window.location.href = "/index.php?r=user/show&id=" + $(this).attr("_userid");
        });
        $("span.user", "div.addon-listing").click(function(){
                window.location.href = "/index.php?r=user/show&id=" + $(this).attr("_userid");
        });
        $("button.submitAddon","a").click(function(){
           window.location.href = $(this).closest("a").attr("href");
        });    
    }
    
    if($("#addon-create").size()>0){
        if($("input[name='AddonForm[action]'][value=1]:first","#addon-create").attr("checked")=="checked")
            $("tr.update").show();
        $("input[name='AddonForm[action]'][value=0]:first","#addon-create").click(function(){
                $("tr.update").hide();
        });
        $("input[name='AddonForm[action]'][value=1]:first","#addon-create").click(function(){
                $("tr.update").show();
        });
    }
	if($("div#widget-mobileList").size()>0){
        $("a[_src]").click(function(){
            Downloader.Download($(this).attr("_src"), "mobile");
        });
    }
	if($("div#widget-effect").size() > 0){
        $.ajax({
            type : 'get',
            url : 'index.php?r=emoticon/getMySequence&user_id='+$("div#pageInfo").attr("_userid"),
            dataType : 'json',
            success : function(data){
                $.each(data, function(idx, obj){$("<option value=\""+obj["hash_id"]+"\" _hashid=\""+obj["hash_id"]+"\">"+obj["name_key"]+"</option>").appendTo("select.effectList","div#widget-effect")});
            }
        });
        $("button.playEffect").click(function(){
			var tempHash;
			if($("select.effectList option[selected=selected]").size()>0)
				tempHash = $("select.effectList option[selected=selected]").attr("_hashid");
			else
				tempHash = $("select.effectList option[selected]").attr("_hashid");
            $.ajax({
                url : 'index.php?r=emoticon/playMotion',
                type : 'get',
                data : {
                    // hash_id : tempHash
					hash_id : $("select.effectList").val()
                },
                success : function(hash){
                    Emoticon.Run(hash, "test");
                }
            });
        });
        $("button.downLoadEffect").click(function(){
            $.ajax({
                url : 'index.php?r=emoticon/downloadMotion',
                type : 'get',
                data : {
                    // hash_id : $("form.effectForm select option[selected]").attr("_hashid")
					hash_id : $("select.effectList").val()
                },
                success : function(hash){
                    Emoticon.Run(hash, "download");
                }
            });
        });
    }
	if($("div#widget-videoList").size()>0){
        $("button").click(function(){
            if($(this).attr("_embedSrc")){
                temp = $(this).attr("_embedSrc");
                if($("div#action-select").size()==0){
                    $("<div id=\"action-select\" />").dialog({
                        title : "Video",
                        width : 500,
                        height : 500,
                        modal : true,
                        resizable : false,
                        buttons : {
                            'Cancel' : function(){
                                $(this).dialog('close')
                            }
                        },
                        open : function(){
                            if($("div#VIDEO_SRC").size()==0)
                                $("<div id=\"VIDEO_SRC\">"+temp+"</div>").appendTo($("div#action-select"));
                            else
                                $("div#VIDEO_SRC").html(temp);
                        }
                    });
                }else {
                    $("#action-select").dialog('open');
                }
            }
            else{
                window.location.href = $(this).attr("_url");
            }
        });
    }
	// Where to buy
    if ($(".map-wrapper").size() > 0){
        $(".map-wrapper").draggable({
            scroll : false,
            containment : '#dummy',
            start : function(){
                $("#country-select-box").val('0');
            }
        });

        $(".map-wrapper > .country > img").hover(function(){
            $(".map-wrapper > .country > img").not(this).mouseout();
            $(this).parent().css("zIndex", 10);
            $(this).animate({
                width : 40,
                height : 30,
                left : -10,
                top : -7.5
            }, {
                queue : false,
                easing : 'easeOutElastic'
            });
        }, function(){
            $(this).parent().css("zIndex", 9);
            $(this).animate({
                width : 20,
                height : 15,
                left : 0,
                top : 0
            }, {
                queue : false,
                easing : 'easeOutElastic',
                complete : function(){
                    $(this).parent().css("zIndex", 9);
                }
            });
        });
        var map = {
            changeMap: function(){
                var country = $("#country-select-box").val();
                var dTop = parseFloat($("div.country."+country).css("top"))*-1 + 150 - 10;
                var dLeft = parseFloat($("div.country."+country).css("left"))*-1 + 490 - 7.5;
                if(!dTop)
                    dTop = -150;
                if(!dLeft)
                    dLeft = -600;
                if (dLeft < -980) dLeft = -980;
                if (dLeft > 1960) dLeft = 1960;
                if (dTop < -938) dTop = -938;
                if (dTop > 938) dTop = 938;
                $(".map-wrapper").animate({
                    top : dTop,
                    left : dLeft
                },{
                    easing : 'easeInExpo',
                    duration : 500,
                    complete : function(){
                        $("div.country."+country+" > img").mouseover();
                    }
                });
            }
        }
        var update = {
            updateList: function(){
                $.post("index.php?r=site/changeCountry",
                    {country_code:$("#country-select-box").val()},
                    function(data){
                        $("div.shopList").html(data);
                    }
                );
                $("p.generic-header:last").html("<span class=\"countryName\"></span>");
                $("span.countryName").html($("option[value="+$("#country-select-box").val()+"]").html());
				if($("option[value="+$("#country-select-box").val()+"]").html()=="Spain")
					$("div.spainShop").show();
				else
					$("div.spainShop").hide();
            }
        }
        $("div.country").click(function(){
            var temp = ($(this).attr("class").split(" "))[1];
            $("#country-select-box").val(temp);
            map.changeMap();
            update.updateList();
        });
        $("#country-select-box").change(function(){
            // console.info($("#country-select-box").val());
            map.changeMap();
            update.updateList();
        });
        map.changeMap();
    }
	if($("div#contact-us").size()>0){
        $("#yt0").show();
        if($("div.sentEmail").size()>0)
            EventLog.Info("Your Email has been sent.");
    }
	//forum
	var editEditorNo = 0;
	if($('#iBuddyPost').size()>0||$('#iBuddyForum').size()>0){
		var editor;
		var editorConfig = {
		    uiColor: '#E0E0E0',
		    toolbar: [
		        ['Bold','Italic','Underline','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','FontSize','-','TextColor','BGColor','-','UploadPhoto']
		    ],
		    //extraPlugins: 'uploadPhoto',
		    filebrowserImageWindowWidth : '1000',
		    filebrowserImageWindowHeight : '600',
		    ImageDlgHideAdvanced: true,
		    ImageDlgHideLink: true
		};
		function createForumEditor(width)
		{
		    if ( editor )
		        return;
		    var html = document.getElementById( 'createPost' ).innerHTML;
		    if($('#iBuddyForum').size()>0){
		    	editorConfig.resize_maxWidth = 932;
		    	editorConfig.resize_minWidth = 932;
		    }
		    else{
		    	editorConfig.resize_maxWidth = 742;
		    	editorConfig.resize_minWidth = 742;
		    }
		    editor = CKEDITOR.replace( 'createPost', editorConfig );
		    editor.setData( html );
		}
		if($('#iBuddyPost').size()>0){
			var config = {
				debug: true
			};
			var dialogConfig = {
				modal : true,
				resizable : false,
				width : 780,
				height : 500
			};
			function postMain(Y){
				function domReady(){
					Y.log('domReady');
					if(Y.one('#createPost'))
						createForumEditor('742px');
					var editorid = 0;
			        var editorName = "";
			        var editor;
			        var reportDialog;
			        var post_info;
			        var editDialog;
			        var editText;
			        $("a.report").click(function(){
			        	var postNo = $(this).parent().prev().prev().prev().children('.postNo').text();
			        	post_info = "post_id="+$('form input[name=post_id]').val()+", post_no="+postNo;
			        	$('div.reportDialog input.reportInfo').val(post_info);
			        	if(!reportDialog){
			        		dialogConfig.title = "Report";
			        		dialogConfig.open = function(){
			    				$(this).children('textarea').show();
			    				$(this).children('textarea').val("");
			    			};
			    			dialogConfig.buttons = {
			    				'submit' : function(){
		            				$.post("index.php?r=site/report",
		                                {
		                					report_text: $('div.reportDialog textarea.reportText').val(),
		                					post_info: post_info
		                                },
		                                function(data){
		                                	if(data)
		                                		EventLog.Info("Your report has been sent");
		                                	else
		                                		EventLog.Error("Your report cannot been sent");
		                                });
		            				$(this).dialog('close');
			                    },
			                    'cancel' : function(){
			                        $(this).dialog('close');
			                    }
			    			};
			        		reportDialog = $('div.reportDialog').dialog(dialogConfig);
			        	}
			        	else
			        		reportDialog.dialog('open');
			        });
			        $('a.edit').click(function(){
			        	editText = $(this).closest('div.postThread').children('div.content').children('div.comment').html();
			        	myId = $(this).closest('div.postThread').children('input').val();
			        	type = $(this).closest('div.postThread').children('input').attr('class');
			        	if(!editDialog){
			        		dialogConfig.title = "Edit";
			        		dialogConfig.open = function(){
			        			$(this).html('<textarea id="editArea_'+editEditorNo+'">'+editText+'</textarea>');
			        			editorConfig.height = 340;
			        			editEditor = CKEDITOR.replace('editArea_'+editEditorNo,editorConfig);
			        			editEditorNo++;
			        		};
			        		dialogConfig.buttons = {
		        				'submit' : function(){
			        				var ajaxFunction = "index.php?r=forum/editComment";
			        				if(type=='id')
			        					ajaxFunction = 'index.php?r=forum/editPost';
			        				$.post(ajaxFunction,
			        						{
			        							commentId: myId,
			        							content: editEditor.getData()
			        						},
			        						function(){
			        							window.location.reload();
			        						}
			        				);
			        				editEditor.destroy();
				                    $(this).dialog('close');
				                },
			        			'cancel' : function(){
			                        $(this).dialog('close');
			                    }
			        		};
			        		editDialog = $('div.editDialog').dialog(dialogConfig);
			        	}
			        	else
			        		editDialog.dialog('open');
			        });
			        $('a.delete').click(function(){
			        	if(confirm('Do you want to delete this comment','Delete Comment')){
			        		Y.log($(this).closest('div.postThread').children('input.post_id'));
			        		$.get('index.php?r=forum/deleteComment',
			        				{
			        					commentId: $(this).closest('div.postThread').children('input.post_id').val()
			        				},
			        				function(data){
			        					if(data)
			        						window.location.reload();
			        				}
			        		);
			        	}
			        });
				}
				Y.on('domready',domReady);
			};
			YUI(config).use('node','event',postMain);
		}
		if($('#iBuddyForum').size()>0){
			var config = {
				debug: true
			};
			function main(Y){
				var editor;
		        function buttonHover(){
		        	this.toggleClass('ui-state-focus');
		        }
				function test(){
					var regex = /&nbsp;/;
					var text = editor.getData();
					text = $.trim(text);
					text = CKEDITOR.tools.trim(text);
					editor.updateElement();
				}
				function animate(el){
		            el.css("backgroundColor", "#CACACA").animate({
		                "backgroundColor" : "#D8D8D8"
		            }, "slow", "linear", function(){
		                $(this).animate({
		                    "backgroundColor" : "#CACACA"
		                }, "slow");
		            });
		        }
				function domReady(){
					Y.log('domReady');
					$('tr.post').hover(function(){
		                animate($(this));
		            }, function(){
		                $(this).stop().css("backgroundColor", "#F0F0F0");
		            });
			        Y.on('mouseover',buttonHover,'input.submit');
			        Y.on('mouseout',buttonHover,'input.submit');
			        Y.on('click',test,'button#test');
			        if(Y.one('#createPost'))
			        	createForumEditor('932px');
				}
				Y.on('domready',domReady);
		        //EventLog.Error("Your Email has been sent.");
			}
		    YUI(config).use('node','event',main);
		}
	}
	
	
	//loginBox
	if($("table#loginBox").size()>0){
        var log = {
            login : function(){
                $("table#loginBox input").attr("disabled","disabled");
                $.post("index.php?r=site/login",
                    {email:$("input#loginEmail").val(),password:$("input#loginPassword").val(),rememberMe:$("input#loginRememberMe").attr("checked")},
                    function(data){
                        if(data)
                            window.location.href = "index.php?r=homePage/listMyHome";
                        else
                            window.location.href = "index.php?r=site/login&error=0";
                    });
            },
            logout : function(){
                $("table#loginBox input").attr("disabled","disabled");
                $.post("index.php?r=site/logout",
                    {},
                    function(data){
						$.cookie("PHPSESSID", null, { path: '/', expires: 10 }); 
                        if(data)
                            window.location.href = "index.php?r=homePage/listMyHome";
                        else
                            window.location.href = "index.php?r=site/login";
                    });
            }
        }
        $("table#loginBox button.login").click(function(){
            log.login();
        });
        $("table#loginBox button.logout").click(function(){
            log.logout();
        });
		$("table#loginBox a.logout").click(function(){
            log.logout();
            return false;
        });
        $("input#loginPassword").keydown(function(evt){
            if(evt.keyCode==13)
                log.login();
        });
        $("input#loginEmail").keydown(function(evt){
            if(evt.keyCode==13)
                log.login();
        });
    }
// Index page flash buttons
    if ($("div.flash-banner").size() > 0){
        maxHeight = $("div.flash-banner").height();
        gapSize = $("div.adv-menu").size()*$("div.adv-menu").size();
        desiredHeight = 120;
        $("div.adv-menu").height((maxHeight - gapSize)/$("div.adv-menu").size());
        normalHeight = $("div.adv-menu").height();

        $("div.adv-menu").hover(function(){
            // animate to height 100px
            $(this).animate({
                height : desiredHeight                
            }, {
                duration : 500,
				queue : false,
                easing : 'easeOutElastic'
            });
            $("div.adv-menu").not($(this)).animate({
                height : normalHeight - (desiredHeight - normalHeight) / ($("div.adv-menu").size() - 1)
            }, {
                duration : 500,
				queue : false,
                easing : 'easeOutElastic'
            });
        }, function(){

            });
			
		var nextMemberList = function(){
            $.get("?r=site/memberRoller", null, function(data){
                i = 0;
                dom = $(data);
                $("img.user-link", dom).load(function(){
                    $(this).closest("div.member-roller").css("top", -140);
                    i++;
                    if (i>=6){
                        $.each($("#widget-search-result > div.member-roller"), function(idx, obj){
                            setTimeout(function(){
                                $(obj).animate({
                                    top: -140
                                },{
                                    complete : function(){
                                        if (idx == 5){
                                            // put back the members
                                            $("#widget-search-result").empty();
                                            dom.appendTo($("#widget-search-result"));
                                            $("img.user-link", $("div.entry[_userid]")).css("cursor", "pointer").click(function(){
                                                window.location.href = "?r=user/show&id=" + $(this).closest("div.entry[_userid]").attr("_userid");
                                            });
                                            $.each($("#widget-search-result > div.member-roller"), function(idx, obj){
                                                setTimeout(function(){
                                                    $(obj).animate({
                                                        top : 0
                                                    }, {
                                                        complete : function(){
                                                            if (idx == 5) setTimeout(nextMemberList, 8000);
                                                        }
                                                    });
                                                }, idx*200);
                                            });                                            
                                        }
                                    }
                                });
                            }, idx*200);
                        });                        
                    }
                });
            });
        }

        setTimeout(nextMemberList, 8000);	
    }
	
	
    
    
    


    // Product Select
    if ($("div.product-select").size() > 0){ 
	
		$("img.tn").imgZoom({
			duration: 500,
			rotate: 1,
			showOverlay: false
		});

        $("#dock2").addDockEffect({
            iconMinSide : 60,
            iconMaxSide : 125,
            distAttDock : 100,
            coefAttDock : 2,
            veloOutDock : 100,
            valign: 'bottom'
        });

		$("div.product-select").css("display", "block");
    }
	
	// Translation
    if (_gTranslate){
        $.each($(".translatable"), function(idx, obj){
            if ($(obj).text != "")
                if (!$(obj).attr("title")){
                    $(obj).attr("title", "Translating :: a moment please...");
                    $(obj).tooltip({
                        track : true,
                        showURL : false,
                        extraClass : "ui-corner-all ui-state-default tips",
                        showBody : "::",
                        delay : 0
                    });
                }
        });

        $(".translatable").hover(function(){
            $("#tooltip").removeAttr("cancel");
            text = $(this).text();
            if ($.trim(text) != ""){
                google.language.detect(text, function(result){
                    if (!result.error && result.language){
                        // console.log(result);
                        myLanguage = "en";
                        switch (_gLang){
                            case ("en-us") : myLanguage = "en"; break;
                            case ("fr-fr") : myLanguage = "fr"; break;
                            case ("es-es") : myLanguage = "es"; break;
                            case ("de-de") : myLanguage = "de"; break;
                            case ("it-it") : myLanguage = "it"; break;
                            case ("nl-nl") : myLanguage = "nl"; break;
                            case ("tr-tr") : myLanguage = "tr"; break;
                            case ("zh-tw") : myLanguage = "zh-TW"; break;
                            case ("zh-cn") : myLanguage = "zh-CN"; break;
                        }

                        if (result.confidence < 0.1){
                            $("#tooltip").css("visibility", "hidden").hide();
                            return;
                        }

                        if (result.language == myLanguage){
                            $("#tooltip").css("visibility", "hidden").hide();
                            return;
                        }

                        google.language.translate(text, result.language, myLanguage, function(result){
                            if (result.translation){
                                $("h3", $("#tooltip")).text("Translation");
                                $(".body", $("#tooltip")).text(result.translation.unescapeHtml());
                                if (!$("#tooltip").attr("cancel"))
                                    $("#tooltip").addClass("ui-corner-all ui-state-default tips").css("visibility", "visible").show();
                            }
                        });
                    }
                });
            }
        }, function(){
            $("#tooltip").attr("cancel", "1").css("visibility", "hidden").hide();
        });
    }
});

google.load("language", "1");
