
//////////// collapsibles ////////
$(document).ready(function()
{
    // hide the all of the element with class clps_body
    // UPDATE: no need because i updated the css
    //$(".clps_body").hide();
    
    // toggle the component with class clps_body
    $(".clps_head").click(function()
    {
        $(this).parent().next(".clps_body").slideToggle("slow");
    });
});
//////////// generic ///////

// a tool to mass replace in a string
// ie: format_str('Hello NAME you are an ugly NAME.', {'NAME':'dude'}) 
// would return: 'Hello dude you are an ugly dude'
function format_str(format, fields) {
    str = format;
    for( key in fields ) {
        // "g" means replace globally, meaning replace all instances of the key.
        regexp = new RegExp(key, "g");
        str = str.replace(regexp, fields[key]);
    }
    return str;
}

//////////// debug ////////
function listProperties(obj) {
    try {
        var propList = "";
        for(var propName in obj) {
           if(typeof(obj[propName]) != "undefined") {
              propList += (propName + ", ");
           }
        }
        alert(propList);
    }
    catch (e) {
      alert("An exception occurred in the script. Error name: " + e.name 
            + ". Error message: " + e.message);
    }
}

//////////// comments ////////
// TODO: erase toggle_comment_form
function toggle_comment_form(id){
    var cform = $('#comment_form_' + id);
    if(cform.hasClass('hidden')) {
        cform.prev().text("בעצם לא");
        cform.slideDown();
    }
    else {
        cform.prev().text("השב");
        cform.slideUp();
    }
    cform.toggleClass('hidden');
}

function add_comment(form, url) {
    form = $(form);
    comment = form.find("#id_comment").val();
    errors_div = form.find("#comment_errors");
    submit = form.find('input.blue_button')
    
    // hide the button so the user won't submit again.
    submit.fadeOut()
    
    // this will be called after posting the comment
    function ajax_comment_callback(data) {
        if( "errors" in data ) {
            errors_div.html(data["errors"]["comment"][0]);
            errors_div.show();
        } else {
            // successful comment
            // animate to tell user that comment was good
            function after_hide_form() {
                form.after('<div id="comment_success" style="display:none; width: 50%; margin: 10px auto; padding: 10px; background-color: #FFA; text-align: center;">תגובתך נרשמה</div>');
                form.next("#comment_success").slideToggle()
            }
            form.slideToggle("slow", after_hide_form);
        }
    }
    
    $.post(url, {"comment" : comment}, ajax_comment_callback, "json");
}

///////////// Bookmarks votes ////////
function vote_href(bookmarks_url, object_id, direction, status) {
    //url = bookmarks_url + object_id + '/' + direction + 'vote/';
    //id = direction + "_" + bookmark_id
    
    //return '<a id="' + id + '" href="#" onclick="vote(' + url + '", ' + bookmark_id + ',' + direction + ') return false;">'
    if (status == "voted") {
        // mod means green/red. Disable this button
        vote_call = '';
        
        // 'mod' means green or red (not grey).
        color = 'mod';
    } else {
        // grey, so allow voting
        color = 'grey';
        vote_fmt = "vote('URL', ID, 'ACTION');";
        if (status == 'can_vote') {
            action = direction;
        } else {
            // 'can_clear'
            action = 'clear';
        }
        vote_call = format_str(vote_fmt, {'URL':bookmarks_url, 'ID':object_id, 'ACTION':action});
    }
    
    href_fmt = '<a id="DIRECTION_ID" href="#" onclick="VOTE return false;"><img src="/site_media/DIRECTION_COLOR.png" alt="vote DIRECTION" />';
    
    fields = {  'DIRECTION': direction,
                'VOTE': vote_call,
                'COLOR': color,
                'ID': object_id
              };
    href = format_str(href_fmt, fields);
    return href
}

function change_vote_color(bookmarks_url, object_id, direction) {
    if (direction == 'up') {
        negative = 'down';
    } else if (direction == 'down') {
        negative = 'up';
    }
    
    // if clear, then both are grey
    if (direction == 'clear') {
        $('#down_' + object_id).replaceWith(vote_href(bookmarks_url, object_id, 'down' ,'can_vote'));
        $('#up_' + object_id).replaceWith(vote_href(bookmarks_url, object_id, 'up', 'can_vote'));
    } else {
        // mod means colorful, so mod up the direction
        // and grey up the negative (and make it able to clear a vote)
        $('#' + direction + '_' + object_id).replaceWith(vote_href(bookmarks_url, object_id, direction, 'voted'));
        $('#' + negative + '_' + object_id).replaceWith(vote_href(bookmarks_url, object_id, negative, 'can_clear'));
    }
}

function vote(bookmarks_url, bookmark_id, direction) {
    var points = $('#bookmark_' + bookmark_id + '_score');
    
    //points.fadeTo(100, 0.1);
    post_url = bookmarks_url + bookmark_id + '/' + direction + 'vote/';
    
    change_vote_color(bookmarks_url, bookmark_id, direction);
    
    function vote_accepted_callback(data) {
        var new_score = data.score.score;
        points.fadeOut(200, function() {
                            points.text(new_score);
                            points.fadeIn(200)
                            }
                            
                      );
    }
    
    $.post(post_url, "", vote_accepted_callback, "json");
}

////////////////// Lightbox Dialogs//////
/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 03/01/2009 +r14
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);

/* init the dialog */
$().ready(function() {
  $('#dialog').jqm();
});
