jQuery(document).ready(function () {
    jQuery("textarea.resizable:not(.processed)").TextAreaResizer();
    jQuery(".fader").children().hover(function () {
        jQuery(this).siblings().stop().fadeTo(500, 0.5)
    }, function () {
        jQuery(this).siblings().stop().fadeTo(500, 1)
    });
    jQuery(".pane:even").addClass("alt");
    jQuery(".pane .btn-delete").click(function () {
        alert("This comment will be deleted!");
        jQuery(this).parents(".pane").animate({
            backgroundColor: "#fbc7c7"
        }, "fast").animate({
            opacity: "hide"
        }, "slow");
        return false
    });
    jQuery(".pane .btn-unapprove").click(function () {
        jQuery(this).parents(".pane").animate({
            backgroundColor: "#fff568"
        }, "fast").animate({
            backgroundColor: "#FFFFE0"
        }, "slow").addClass("spam");
        return false
    });
    jQuery(".pane .btn-approve").click(function () {
        jQuery(this).parents(".pane").animate({
            backgroundColor: "#dafda5"
        }, "fast").animate({
            backgroundColor: "#EDFED3"
        }, "slow").removeClass("spam");
        return false
    });
    jQuery(".pane .btn-spam").click(function () {
        jQuery(this).parents(".pane").animate({
            backgroundColor: "#fbc7c7"
        }, "fast").animate({
            opacity: "hide"
        }, "slow");
        return false
    })
});

(function (a) {
    a.fn.dgComments = function (b) {
        a(this).click(function () {
            var e = a("#cmtpic").val();
            var d = a("#cmtname").val();
            var c = a("#cmtmail").val();
            var h = a("#cmttext").val();
            var f = a("#captchaTxt").val();
            var g = "cmtpic=" + e + "&cmtname=" + d + "&cmtmail=" + c + "&cmttext=" + h + "&captchaTxt=" + f;
            a.ajax({
                type: "post",
                url: b,
                data: g,
                cache: false,
                success: function (j) {
                    refreshCaptcha();
                    var i = a("ul#list li:last").attr("class");
                    if (i == "error") {
                        a("ul#list li:last").remove()
                    }
                    a("div#nocom").replaceWith("<ul id='list'></ul>");
                    a("ul#list").append(j);
                    var i = a("ul#list li:last").attr("class");
                    if (i == "error") {
                        a("ul#list li:last").hide().slideDown(400, function () {
                            a(this).animate({
                                opacity: "1.0"
                            }, 5000, function () {
                                a(this).slideUp(150)
                            })
                        })
                    }
                }
            });
            return false
        })
    }
})(jQuery);

(function (d) {
    d.each(["backgroundColor", "borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor", "color", "outlineColor"], function (f, e) {
        d.fx.step[e] = function (g) {
            if (g.state == 0) {
                g.start = c(g.elem, e);
                g.end = b(g.end)
            }
            g.elem.style[e] = "rgb(" + [Math.max(Math.min(parseInt((g.pos * (g.end[0] - g.start[0])) + g.start[0]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[1] - g.start[1])) + g.start[1]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[2] - g.start[2])) + g.start[2]), 255), 0)].join(",") + ")"
        }
    });

    function b(f) {
        var e;
        if (f && f.constructor == Array && f.length == 3) {
            return f
        }
        if (e = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)) {
            return [parseInt(e[1]), parseInt(e[2]), parseInt(e[3])]
        }
        if (e = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)) {
            return [parseFloat(e[1]) * 2.55, parseFloat(e[2]) * 2.55, parseFloat(e[3]) * 2.55]
        }
        if (e = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)) {
            return [parseInt(e[1], 16), parseInt(e[2], 16), parseInt(e[3], 16)]
        }
        if (e = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)) {
            return [parseInt(e[1] + e[1], 16), parseInt(e[2] + e[2], 16), parseInt(e[3] + e[3], 16)]
        }
        return a[d.trim(f).toLowerCase()]
    }
    function c(g, e) {
        var f;
        do {
            f = d.curCSS(g, e);
            if (f != "" && f != "transparent" || d.nodeName(g, "body")) {
                break
            }
            e = "backgroundColor"
        } while (g = g.parentNode);
        return b(f)
    }
    var a = {
        aqua: [0, 255, 255],
        azure: [240, 255, 255],
        beige: [245, 245, 220],
        black: [0, 0, 0],
        blue: [0, 0, 255],
        brown: [165, 42, 42],
        cyan: [0, 255, 255],
        darkblue: [0, 0, 139],
        darkcyan: [0, 139, 139],
        darkgrey: [169, 169, 169],
        darkgreen: [0, 100, 0],
        darkkhaki: [189, 183, 107],
        darkmagenta: [139, 0, 139],
        darkolivegreen: [85, 107, 47],
        darkorange: [255, 140, 0],
        darkorchid: [153, 50, 204],
        darkred: [139, 0, 0],
        darksalmon: [233, 150, 122],
        darkviolet: [148, 0, 211],
        fuchsia: [255, 0, 255],
        gold: [255, 215, 0],
        green: [0, 128, 0],
        indigo: [75, 0, 130],
        khaki: [240, 230, 140],
        lightblue: [173, 216, 230],
        lightcyan: [224, 255, 255],
        lightgreen: [144, 238, 144],
        lightgrey: [211, 211, 211],
        lightpink: [255, 182, 193],
        lightyellow: [255, 255, 224],
        lime: [0, 255, 0],
        magenta: [255, 0, 255],
        maroon: [128, 0, 0],
        navy: [0, 0, 128],
        olive: [128, 128, 0],
        orange: [255, 165, 0],
        pink: [255, 192, 203],
        purple: [128, 0, 128],
        violet: [128, 0, 128],
        red: [255, 0, 0],
        silver: [192, 192, 192],
        white: [255, 255, 255],
        yellow: [255, 255, 0]
    }
})(jQuery);

(function (j) {
    var g, h;
    var c = 0;
    var a = 32;
    var d;
    j.fn.TextAreaResizer = function () {
        return this.each(function () {
            g = j(this).addClass("processed"), h = null;
            j(this).wrap('<div class="resizable-textarea"><span></span></div>').parent().append(j('<div class="grippie"></div>').bind("mousedown", {
                el: this
            }, b));
            var k = j("div.grippie", j(this).parent())[0];
            k.style.marginRight = (k.offsetWidth - j(this)[0].offsetWidth) + "px"
        })
    };

    function b(k) {
        g = j(k.data.el);
        g.blur();
        c = i(k).y;
        h = g.height() - c;
        g.css("opacity", 0.25);
        j(document).mousemove(f).mouseup(e);
        return false
    }
    function f(m) {
        var k = i(m).y;
        var l = h + k;
        if (c >= (k)) {
            l -= 5
        }
        c = k;
        l = Math.max(a, l);
        g.height(l + "px");
        if (l < a) {
            e(m)
        }
        return false
    }
    function e(k) {
        j(document).unbind("mousemove", f).unbind("mouseup", e);
        g.css("opacity", 1);
        g.focus();
        g = null;
        h = null;
        c = 0
    }
    function i(k) {
        return {
            x: k.clientX + document.documentElement.scrollLeft,
            y: k.clientY + document.documentElement.scrollTop
        }
    }
})(jQuery);

function vote(c, g, l, f, a) {
    var h = window.location;
    var k = h.protocol + "//" + h.host + sfolder;
    var d;
    var b = document.getElementById("vote_" + c);
    b.innerHTML = '<img src="' + k + '/components/com_datsogallery/images/loading.gif" border="0" style="vertical-align:middle" /> ' + vote_msg[1];
    try {
        d = new XMLHttpRequest()
    } catch (j) {
        try {
            d = new ActiveXObject("Msxml2.XMLHTTP")
        } catch (j) {
            try {
                d = new ActiveXObject("Microsoft.XMLHTTP")
            } catch (j) {
                alert(vote_msg[0]);
                return false
            }
        }
    }
    d.onreadystatechange = function () {
        var e;
        if (d.readyState == 4) {
            setTimeout(function () {
                e = d.responseText;
                if (e == "thanks") {
                    b.innerHTML = '<span class="vote-msg-thanks">' + vote_msg[2] + "</span>"
                }
                if (e == "voted") {
                    b.innerHTML = '<span class="vote-msg-voted">' + vote_msg[3] + "</span>"
                }
            }, 1000);
            setTimeout(function () {
                if (e == "thanks") {
                    var m = f + 1;
                    var i = ((l + g) / (m));
                    document.getElementById("rating_" + c).style.width = parseInt(i * 20) + "%"
                }
                if (a != 0) {
                    if (e == "thanks") {
                        if (m != 1) {
                            var n = vote_msg[4] + ": " + m
                        } else {
                            var n = vote_msg[5] + ": " + m
                        }
                        b.innerHTML = '<span class="vote-msg">( ' + n + " )</span>"
                    } else {
                        if (f != 0 || a != -1) {
                            if (f != 1) {
                                var o = vote_msg[4] + ": " + f
                            } else {
                                var o = vote_msg[5] + ": " + f
                            }
                            b.innerHTML = '<span class="vote-msg">( ' + o + " )</span>"
                        } else {
                            b.innerHTML = ""
                        }
                    }
                } else {
                    b.innerHTML = ""
                }
            }, 2000)
        }
    };
    d.open("GET", k + "/index.php?option=com_datsogallery&func=vote&rating=" + g + "&id=" + c +"&format=raw", true);
    d.send(null)
}

(function (d) {
    d.fn.editInPlace = function (e) {
        var f = d.extend({}, d.fn.editInPlace.defaults, e);
        b(f.saving_image);
        return this.each(function () {
            var g = d(this);
            if (g.data("editInPlace")) {
                return
            }
            g.data("editInPlace", true);
            new c(f, g).init()
        })
    };
    d.fn.editInPlace.defaults = {
        url: "",
        bg_img_over: "",
        bg_img_out: "",
        hover_class: "",
        show_buttons: false,
        save_button: '<button class="inplace_save">Save</button>',
        cancel_button: '<button class="inplace_cancel">Cancel</button>',
        params: "",
        field_type: "text",
        default_text: "(Click here to add text)",
        textarea_rows: 10,
        textarea_cols: 25,
        select_text: "Choose new value",
        select_options: "",
        saving_text: "Saving...",
        saving_image: "",
        value_required: false,
        element_id: "element_id",
        update_value: "update_value",
        original_html: "original_html",
        save_if_nothing_changed: false,
        on_blur: "save",
        callback: null,
        success: null,
        error: function (e) {
            this.reportError("Failed to save value: " + e.responseText || "Unspecified Error")
        },
        error_sink: function (e, f) {
            alert(f)
        }
    };

    function c(e, f) {
        this.settings = e;
        this.dom = f;
        this.originalHTML = null;
        this.originalText = null;
        this.didInsertDefaultText = false
    }
    d.fn.editInPlace.InlineEditor = c;
    d.extend(c.prototype, {
        init: function () {
            this.setDefaultTextIfNeccessary();
            this.connectEvents()
        },
        setDefaultTextIfNeccessary: function () {
            if ("" !== this.dom.html()) {
                return
            }
            this.dom.html(this.settings.default_text);
            this.didInsertDefaultText = true
        },
        connectEvents: function () {
            var e = this;
            this.dom.bind("mouseenter.editInPlace", function () {
                e.mouseEnter()
            }).bind("mouseleave.editInPlace", function () {
                e.mouseLeave()
            }).bind("click.editInPlace", function () {
                e.handleClickOnClosedEditor()
            })
        },
        mouseEnter: function () {
            this.addHover()
        },
        mouseLeave: function () {
            this.removeHover()
        },
        addHover: function () {
            if (this.settings.hover_class) {
                this.dom.addClass(this.settings.hover_class)
            } else {
                this.dom.css("background", this.settings.bg_img_over)
            }
        },
        removeHover: function () {
            if (this.settings.hover_class) {
                this.dom.removeClass(this.settings.hover_class)
            } else {
                this.dom.css("background", this.settings.bg_img_out)
            }
        },
        handleClickOnClosedEditor: function () {
            this.dom.unbind(".editInPlace");
            this.removeHover();
            if (this.didInsertDefaultText && this.dom.html() === this.settings.default_text) {
                this.dom.html("");
                this.didInsertDefaultText = false
            }
            this.originalHTML = this.dom.html();
            this.originalText = a(this.dom.text());
            this.replaceContentWithEditor();
            this.connectEventsToEditor()
        },
        replaceContentWithEditor: function () {
            var f = (this.settings.show_buttons) ? "<div style=\"padding-top:10px\">" + this.settings.save_button + " " + this.settings.cancel_button + "</div>" : "";
            var e = this.createEditorElement();
            this.dom.html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;border-top:1px solid #ccc"></form>').find("form").append(e).append(f)
        },
        createEditorElement: function () {
            if (-1 === d.inArray(this.settings.field_type, ["text", "textarea", "select"])) {
                throw "Unknown field_type <fnord>, supported are 'text', 'textarea' and 'select'"
            }
            if ("select" === this.settings.field_type) {
                return this.createSelectEditor()
            }
            var e = null;
            if ("text" === this.settings.field_type) {
                e = d('<input type="text"' + this.inputNameAndClass() + "/>")
            } else {
                if ("textarea" === this.settings.field_type) {
                    e = d("<textarea" + this.inputNameAndClass() + 'rows="' + this.settings.textarea_rows + '" cols="' + this.settings.textarea_cols + '" style="width:99%"></textarea>')
                }
            }
            e.val(this.originalText);
            return e
        },
        inputNameAndClass: function () {
            return ' name="inplace_value" class="inplace_field" '
        },
        createSelectEditor: function () {
            var k = d("<select" + this.inputNameAndClass() + '><option disabled="true" value="">' + this.settings.select_text + "</option></select>");
            var f = this.settings.select_options;
            if (!d.isArray(f)) {
                f = f.split(",")
            }
            for (var g = 0; g < f.length; g++) {
                var e = f[g];
                if (!d.isArray(e)) {
                    e = e.split(":")
                }
                var l = a(e[1] || e[0]);
                var m = a(e[0]);
                var j = (l == this.originalText) ? 'selected="selected" ' : "";
                var h = d("<option " + j + " ></option>").val(l).text(m);
                k.append(h)
            }
            return k
        },
        connectEventsToEditor: function () {
            var h = this;

            function g() {
                h.handleCancelEditor();
                return false
            }
            function e() {
                h.handleSaveEditor();
                return false
            }
            var f = this.dom.find("form");
            f.find(".inplace_field").focus().select();
            f.find(".inplace_cancel").click(g);
            f.find(".inplace_save").click(e);
            if (!this.settings.show_buttons) {
                if ("save" === this.settings.on_blur) {
                    f.find(".inplace_field").blur(e)
                } else {
                    f.find(".inplace_field").blur(g)
                }
                if (d.browser.mozilla) {
                    f.keyup(function (i) {
                        if (13 === i.which) {
                            e()
                        }
                    })
                }
            }
            f.keyup(function (i) {
                if (27 === i.which) {
                    return g()
                }
            });
            f.submit(e)
        },
        handleCancelEditor: function () {
            this.init();
            this.dom.html(this.originalHTML)
        },
        handleSaveEditor: function () {
            var e = this.dom.find(":input").val();
            if (this.isDisabledDefaultSelectChoice() || this.isUnchangedInput(e)) {
                this.handleCancelEditor();
                return
            }
            if (this.settings.value_required && ("" === e || undefined === e)) {
                this.dom.html(this.originalHTML);
                this.init();
                this.reportError("Error: You must enter a value to save this field");
                return
            }
            this.showSavingMessage();
            if (this.settings.callback) {
                this.handleSubmitToCallback(e)
            } else {
                this.handleSubmitToServer(e)
            }
        },
        isDisabledDefaultSelectChoice: function () {
            return this.dom.find("option").eq(0).is(":selected:disabled")
        },
        isUnchangedInput: function (e) {
            return !this.settings.save_if_nothing_changed && this.originalText === e
        },
        showSavingMessage: function () {
            var e = this.settings.saving_text;
            if ("" !== this.settings.saving_image) {
                e = '<div style="display:block;text-align:center;padding-top:30px"><img src="' + this.settings.saving_image + '" alt="Saving..." /></div>'
            }
            this.dom.html(e)
        },
        handleSubmitToCallback: function (e) {
            var f = this.settings.callback(this.id(), e, this.originalHTML, this.settings.params);
            this.init();
            if (undefined === f) {
                this.reportError("Error: Failed to save value: " + e);
                this.dom.html(this.originalHTML);
                return
            }
            this.dom.html(f)
        },
        handleSubmitToServer: function (e) {
            var g = this.settings.update_value + "=" + encodeURIComponent(e) + "&" + this.settings.element_id + "=" + this.dom.attr("id") + (("" !== this.settings.params) ? "&" + this.settings.params : "") + "&" + this.settings.original_html + "=" + encodeURIComponent(this.originalHTML);
            var f = this;
            d.ajax({
                url: f.settings.url,
                type: "POST",
                data: g,
                dataType: "html",
                complete: function (h) {
                    f.init()
                },
                success: function (i) {
                    var h = i || f.settings.default_text;
                    f.dom.html(h);
                    if (f.settings.success) {
                        f.settings.success.apply(f, [i, f.dom])
                    }
                },
                error: function (h) {
                    f.dom.html(f.originalHTML);
                    if (f.settings.error) {
                        f.settings.error.apply(f, [h, f.dom])
                    }
                }
            })
        },
        reportError: function (e) {
            if (this.settings.error_sink) {
                this.settings.error_sink.apply(this, [this.id(), e])
            }
        },
        id: function () {
            return this.dom.attr("id")
        },
        missingCommaErrorPreventer: ""
    });

    function b(f) {
        if ("" === f) {
            return
        }
        var e = new Image();
        e.src = f
    }
    function a(e) {
        return e.replace(/^\s+/, "").replace(/\s+$/, "")
    }
})(jQuery);

jQuery(document).ready(function() {
    jQuery("#addtobasket").click(function () {
        var id = jQuery(this).attr("class");
        var dataString = 'id=' + id;
        jQuery(this).css({opacity: '0.4'}, 50);
        jQuery.ajax({
            type: "post",
            url: siteurl + 'index.php?option=com_datsogallery&func=addtobasket&format=raw',
            data: dataString,
            cache: false,
            success: function (html) {
                update_subtotal();
                jQuery(".dg_slider").html(html);
                if (jQuery(".dg_slider").is(":hidden")) {
                  jQuery(".dg_slider").html(html).show();
                  }
                  else {
                      jQuery(".dg_slider").html(html);
                  }
                  if (jQuery(".imgtitle_basket").is(":hidden")) {
                  jQuery(".imgtitle_basket").show();
                  }
                  else {
                      jQuery(".imgtitle_basket");
                  }
            }
        });
        return false;
    });
});


function update_subtotal() {
    var subtotal = jQuery("#subtotal");
    jQuery.ajax({
        type: 'post',
        url: siteurl + 'index.php?option=com_datsogallery&func=subtotal&format=raw',
        cache: false,
        success: function (html) {
            subtotal.html(html);
            update_items();
        }
    });
}

function update_total() {
    var total = jQuery("#total");
    var amount = jQuery("input[name='amount']");
    jQuery.ajax({
        type: 'post',
        url: siteurl + 'index.php?option=com_datsogallery&func=total&format=raw',
        cache: false,
        success: function (html) {
            total.html(html);
            amount.val(html);
        }
    });
}
function update_items() {
    var items = jQuery("#items");
    jQuery.ajax({
        type: 'post',
        url: siteurl + 'index.php?option=com_datsogallery&func=updateitems&format=raw',
        cache: false,
        success: function (response) {
            items.html(response);
        }
    });
}
jQuery(document).ready(function() {
	jQuery('.btn-delete').click(function() {
		var parent = jQuery(this).parent().parent();
		jQuery.ajax({
			type: 'post',
			url: siteurl + 'index.php?option=com_datsogallery&func=deletecomment&format=raw',
			data: 'cmtid=' + parent.attr('id'),
            cache: false
		});
	});
    jQuery('.btn-approve').click(function() {
		var parent = jQuery(this).parent().parent();
		jQuery.ajax({
			type: 'post',
			url: siteurl + 'index.php?option=com_datsogallery&func=approvecomment&format=raw',
			data: 'cmtid=' + parent.attr('id'),
            cache: false
		});
	});
    jQuery('.btn-unapprove').click(function() {
		var parent = jQuery(this).parent().parent();
		jQuery.ajax({
			type: 'post',
			url: siteurl + 'index.php?option=com_datsogallery&func=unapprovecomment&format=raw',
			data: 'cmtid=' + parent.attr('id'),
            cache: false
		});
	});
    jQuery('.btn-spam').click(function() {
		var parent = jQuery(this).parent().parent();
		jQuery.ajax({
			type: 'post',
			url: siteurl + 'index.php?option=com_datsogallery&func=spamcomment&format=raw',
			data: 'cmtid=' + parent.attr('id'),
            cache: false
		});
	});
});

    function refreshCaptcha(captchaPath){
	if(!captchaPath) captchaPath = siteurl + 'index.php?option=com_datsogallery&func=captcha&format=raw';
	document.getElementById('captcha').src = captchaPath + '&' + Math.random();
	document.getElementById('captchaTxt').value='';
	document.getElementById('captchaTxt').focus();

}
jQuery(document).ready(function() {
           jQuery('#btn-submit').dgComments(siteurl + 'index.php?option=com_datsogallery&func=commentadd&format=raw');
        });
    jQuery(document).ready(function () {
        jQuery("span.add_favorite").mouseover(function () {
            jQuery(this).addClass("add_favorite_hover");
        });

        jQuery("span.add_favorite").mouseout(function () {
            jQuery(this).removeClass("add_favorite_hover");
        });
    });

    jQuery(function () {
        jQuery(".favorite").click(function () {
            var id = jQuery(this).attr("id");
            var dataString = 'id=' + id;
            var parent = jQuery(this);

            jQuery(this).css({opacity: '0.4'}, 50);
            jQuery.ajax({
                type: "post",
                url: siteurl + 'index.php?option=com_datsogallery&func=addtofavorites&format=raw',
                data: dataString,
                cache: false,

                success: function (html) {
                    parent.html(html);
                    parent.animate({opacity: '1.0'}, 300);
                }
            });


            return false;

        });
    });

jQuery(document).ready(function() {
  jQuery('.dgtip').dgtooltip({gravity: 's', fade: true, html: true});
});
