var cid = -1,
    memory = 0,
    result = "",
    naction = "",
    res = false;

function showCalc(elm){
    var calc = $("#calc"),
        blind = $('<div id="mask"></div>'),
        pageHeight = $('#wrapper').height();

    cid = elm.attr("class").replace("calc_","");
    blind.height(pageHeight).appendTo('body').show();
    calc.appendTo("div.cbox_"+cid).css({'top':"-"+(calc.height()/2), 'left': "-"+(calc.width()+100)}).fadeIn();
}

function resetCalc(elm,all){
    memory = 0;
    naction = "";
    elm.val("");
    result = "";
    res = false;
    if(all){
        $("#calc").hide();
	    $("#mask").remove();
    }
}

$.fn.appendVal = function(txt) {
   return this.each(function(){
       this.value += txt;
   });
};


$(function(){

    var holder = $("#calc input.ctext");

    $("#calc input").click(function(){
        var type = $(this).attr("class");

        switch (type) {
            case "cnum":
                if(naction != "" && !res) {
                    holder.val("");
                    res = true;
                }
                holder.appendVal($(this).val());
                break;
            case "cact":
                var action =  $(this).val();
                switch (action) {
                    case "=":
                        if(naction == "+") result = memory+parseFloat(holder.val());
                        if(naction == "-") result = memory-parseFloat(holder.val());
                        if(naction == "*") result = memory*parseFloat(holder.val());
                        if(naction == "/") result = memory/parseFloat(holder.val());
                        if(result != "") {
                            holder.val(result);
                            res = false;
                        }
                        break;
                    case "C":
                        resetCalc(holder,false);
                        break;
                    default:
                        if(holder.val() != "") {
                            naction =  $(this).val();
                            memory = parseFloat(holder.val());
                        }
                }
                break;
            case "cadd":
                $("input.vals_"+cid).val(Math.round(Math.abs(holder.val())));
                resetCalc(holder,true);
                break;
            default:
                return false;
        }

        return false;
    });

    $("#calc #cclose").click(function(){
        resetCalc(holder,true);
        return false;
    });

})

