// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var page = {}
var community = {}
var organization = {}
var user = false
var user_can_vote = false
var no_permission_for_vote = false

function idea_search_select_category() {
    box = $('available_categories');
    index = box.selectedIndex;
    option_selected = box.options[index];
    value = option_selected.value;
    long_name = option_selected.innerHTML;
    idea_search_add_category(long_name, value);
}

function idea_search_add_category(long_name, id) {
    if ($('added_category_' + id) == null) {
        remove_tag = "<a href='#' onClick='idea_search_remove_category(" + id + "); return false;'><img src='/images/red_x.png'/>";
        text = "<div id='added_category_" + id + "'><img src='/images/check.png'/>" + long_name;
        text += remove_tag;
        text += "</div>";
        $('query_communities').value = $('query_communities').value + " " + id;
        new Insertion.Bottom("search_selected_categories", text);
        $('search_results').innerHTML = '';
    }
}

function idea_search_remove_category(id) {
    $('added_category_' + id).remove();
    re = new RegExp(" " + id);
    $('query_communities').value = $('query_communities').value.replace(re,'');
    $('search_results').innerHTML = '';
}

function toggle_div(id){
    link = $(id+"_link")
    ele =  $(id+"_children")
	  if(!ele) {return false;}	
    if ( ele.visible() ){link.removeClassName("open")}
    else{link.addClassName("open")}	
    new Effect.toggle(ele,'Blind', {duration:.1});
}

function toggle_category(id){
    link = $(id+"_link")
    h4value = link.up('h4')
    ele =  $(id+"_children")
	  if(!ele) {return false;}	
    if ( ele.visible() ){h4value.removeClassName("open")}
    else{h4value.addClassName("open")}	
    new Effect.toggle(ele,'Blind', {duration:.1});
}

var IdeaVote = {};
IdeaVote = Class.create({
    initialize: function(idea_id){
        this.idea_id = idea_id.split("_")[1]
        this.idea_css_id = "#"+idea_id

		    this.mouseover_timer = null

        this.idea_vote_block = $$(this.idea_css_id+" .vote_controls")[0]
		    this.vote_controls_css = this.idea_vote_block.className
		    
        this.up_arrow = $$(this.idea_css_id+" .vote_up")[0]
        this.down_arrow = $$(this.idea_css_id+" .vote_down")[0]
	      
        this.up_one = $$(this.idea_css_id+" .vote_up_1")[0]
        this.up_two = $$(this.idea_css_id+" .vote_up_2")[0]
        this.up_three = $$(this.idea_css_id+" .vote_up_3")[0]
	      
        this.down_one = $$(this.idea_css_id+" .vote_down_1")[0]
        this.down_two = $$(this.idea_css_id+" .vote_down_2")[0]
        this.down_three = $$(this.idea_css_id+" .vote_down_3")[0]
	      
        this.rating = $$(this.idea_css_id+" .idea_rating")[0]
	      
        this.init_observers();
	      
        this.users_current_vote = 0
    },
    init_observers: function(){
		    this.up_one.observe('mouseover', this.mouseover.bindAsEventListener(this,1))
		    this.up_two.observe('mouseover', this.mouseover.bindAsEventListener(this,2))
		    this.up_three.observe('mouseover',this.mouseover.bindAsEventListener(this,3))
		    this.down_one.observe('mouseover', this.mouseover.bindAsEventListener(this, -1))
		    this.down_two.observe('mouseover', this.mouseover.bindAsEventListener(this, -2))
		    this.down_three.observe('mouseover',this.mouseover.bindAsEventListener(this, -3))
		    //   This is done according to bug AI - 7396
        this.up_one.observe('mouseout', this.mouseout.bindAsEventListener(this,1))
		    this.up_two.observe('mouseout', this.mouseout.bindAsEventListener(this,2))
		    this.up_three.observe('mouseout',this.mouseout.bindAsEventListener(this,3))
		    this.down_one.observe('mouseout', this.mouseout.bindAsEventListener(this, -1))
		    this.down_two.observe('mouseout', this.mouseout.bindAsEventListener(this, -2))
		    this.down_three.observe('mouseout',this.mouseout.bindAsEventListener(this, -3))
		    
		    if(!user_can_vote && !no_permission_for_vote){

			      this.idea_vote_block.getElementsBySelector('a').each(function(link){
				        init_login_link(link)
			      },this)
			          return;
		    }
        if(no_permission_for_vote){
		 	      this.idea_vote_block.getElementsBySelector('a').each(function(link){
				        init_error_link(link,"/communities/"+community.permalink+"/vote/Idea/"+this.idea_id+"/0")
			      },this)
			          return;
		    }

        this.up_arrow.observe("click", this.increment_vote.bindAsEventListener(this))
        this.down_arrow.observe('click', this.decrement_vote.bindAsEventListener(this))
        this.up_one.observe('click', this.set_vote.bindAsEventListener(this, 1))
        this.up_two.observe('click', this.set_vote.bindAsEventListener(this, 2))
        this.up_three.observe('click', this.set_vote.bindAsEventListener(this, 3))
        this.down_one.observe('click', this.set_vote.bindAsEventListener(this, -1))
        this.down_two.observe('click', this.set_vote.bindAsEventListener(this, -2))
        this.down_three.observe('click', this.set_vote.bindAsEventListener(this, -3))
    },
    increment_vote: function(e){
        if(this.users_current_vote == 3){return}
	      
        if(this.users_current_vote == -1){this.set_users_vote(2)}
        else{this.set_users_vote(1)}
		    e.stop();
    },
    decrement_vote: function(e){
        if(this.users_current_vote == -3){return}		
	      
        if(this.users_current_vote == 1){this.set_users_vote(-2)}
        else{this.set_users_vote(-1)}
		    e.stop();
    },
    set_vote: function(e){
        vote = arguments[1]
        this.users_current_vote = vote
        this.record();	
		    e.stop();
    },
    set_users_vote: function(vote){
        this.users_current_vote += vote;
        this.record();
    },
    vote_loader_show: function(){
            $("vote_loader_"+this.idea_id).removeClassName("loader_hidden");
            $("vote_loader_"+this.idea_id).addClassName("loader_visible");

    },
    vote_loader_hide: function(){
            $("vote_loader_"+this.idea_id).removeClassName("loader_visible");
            $("vote_loader_"+this.idea_id).addClassName("loader_hidden");
    },
    record: function(){
        var that = this; // pre-caching the "this" here for use within the AJAX handlers below. (the "this" within AJAX handlers point to the window object.)
        url = "/communities/"+community.permalink+"/vote/Idea/"+this.idea_id+"/"+this.users_current_vote;
        new Ajax.Request(url, {method: 'post', 
                               onLoading: function() {
                                  that.idea_vote_block.hide();
                                  that.vote_loader_show();
                               },
                               onComplete: function(resp) {
                                  that.vote_loader_hide();
                                  that.idea_vote_block.show();
                                  that.update_rating.apply(that, [resp]);
                               }
                              });
    },

	  mouseover: function(e){
		    countdown_from = arguments[1]
		    
		    //clearTimeout(this.mouseover_timer)
		    //this.mouseover_timer = setTimeout(this.countdown.bindAsEventListener(this, countdown_from), 1000)
		    
		    if(countdown_from > 0){
			      this.idea_vote_block.className = this.vote_controls_css 
			      this.idea_vote_block.addClassName("vote_up_hover_"+countdown_from)
		    }else{
			      this.idea_vote_block.className = this.vote_controls_css 
			      this.idea_vote_block.addClassName("vote_down_hover_"+countdown_from*-1)			
		    }
	  },
    mouseout: function(e){
        this.idea_vote_block.className = this.vote_controls_css
    },
	  countdown: function(e){
		    countdown_from = arguments[1]
		    modifier = countdown_from > 0 ? -1 : +1
		    next_countdown = ((50 * (countdown_from*modifier))).abs()

		    //we are at the bottom of the rung, lets get out of here.
		    if(countdown_from == 0 || countdown_from == this.users_current_vote){ 
			      // console.log("Stop that shit!")	
			      this.idea_vote_block.className = this.vote_controls_css
			      clearTimeout(this.mouseover_timer); 
			      return; 
		    }
		    
		    if(countdown_from > 0){
			      this.idea_vote_block.className = this.vote_controls_css 
			      this.idea_vote_block.addClassName("vote_up_hover_"+(countdown_from+modifier))
		    }else{
			      this.idea_vote_block.className = this.vote_controls_css 
			      this.idea_vote_block.addClassName("vote_down_hover_"+((countdown_from+modifier)*-1))	
		    }

		    this.mouseover_timer = setTimeout(this.countdown.bindAsEventListener(this, countdown_from+modifier), next_countdown)
	  },
    update_rating: function(resp){
		    class_name = "voted_"+(this.users_current_vote > 0 ? "up" : "down")+"_"+this.users_current_vote.abs()
		    this.vote_controls_css = this.idea_vote_block.className = "vote_controls "+class_name;
		    
        if(resp.responseText ==''){
       	    alert('You do not have permission to perform this action.');
            window.location.reload();
        }else
            this.rating.update(resp.responseText);
    }
});

var Tabber = {}
Tabber = Class.create({
	  construct: function(){
		    $$('ul.tab_controls li').each(function(li){
			      // console.log(li)
			      //show if we are default
			      if(li.readAttribute('default')){
				        $(li.readAttribute("target_id")).show();
			      }else{
				        $(li.readAttribute("target_id")).hide();				
			      }
			      //replace the HTML title inside with a link
			      li.innerHTML = "<a href='#'>"+li.innerHTML+"</a>"
			      anchor = li.down('a')
			      anchor.observe('click', this.showYourself.bindAsEventListener(anchor))
		    }, this)
	          },
	  is_default: function(){
		    this.readAttribute('default') ? true : false
	  },
	  showYourself: function(e){
		    //hide currently visiable elements in this child's parent
		    // console.log('showing')
		    this.up('ul').nextSiblings().each(function(li){
			      li.hide()
		    })
		        
		        //remove all active css tags
		        this.up('ul').getElementsBySelector("a").each(function(link){
			          link.removeClassName("active")
			          if(link == this){
				            link.addClassName('active')
			          }
		        },this)

		            //show the div related to this element
		            $(this.up('li').readAttribute('target_id')).show();
		    Event.stop(e)

    }
});
tabber = new Tabber();
Event.observe(window,'load', tabber.construct.bindAsEventListener(tabber))

function init_tabber_for_lightwindow(){
	  tabber = new Tabber();
	  tabber.construct();
}

function toggle_edit_field(id) {
    form_div = $('form_field_' + id);
    toggle_anchor = $('toggle_edit_field_' + id);
    if (toggle_anchor.classNames().include('edit')) {
        form_div.show();
        toggle_anchor.removeClassName('edit')
        toggle_anchor.addClassName('mini')
    } else {
        form_div.hide();
        toggle_anchor.removeClassName('mini')
        toggle_anchor.addClassName('edit')
    }
}

var LiveSearch = {}
LiveSearch = Class.create({
	  construct: function(){
	      
		    //find elements
		    this.search_form = $('idea_live_search')
		    this.search_field = $("idea_query_field")
        this.create_form = $('idea_live_search1')
        this.create_field = $("idea_query_field1")
		    //catch no form
        if((!this.search_field || !this.search_form)&&(!this.create_form||!this.create_field)){return false;}
        if(this.search_form)
        {
            this.button = Form.getInputs('idea_live_search', 'submit')[0]
            //set focus actions
            this.search_field.observe('focus', function(e){e.element().value ='';e.element().style.color='#666';e.element().style.textAlign='left'})
            // this.search_field.observe('blur', function(e){e.element().value =''; e.element().style.color='#666'; e.element().style.textAlign='left'})
            //catch the submit
            this.search_form.observe('submit', this.fetch.bindAsEventListener(this))
        }
		    
        if(this.create_form)
        {        
            this.find_button = Form.getInputs('idea_live_search1','submit')
            this.create_field.observe('focus', function(e){e.element().value ='';e.element().style.color='#666';e.element().style.textAlign='left'})
            //catch the submit
            this.create_form.observe('submit', this.fetch.bindAsEventListener(this))
        }	
	  },
	  fetch: function(e){
        search_create = $('create_search_block').value;
        if(search_create == 1 ){
            new Ajax.Request('/communities/'+community.permalink+"/ideas/live_search", {method: 'post', parameters: "search_string="+this.create_field.value + "&search_value="+search_create})        
        }
        else{
            new Ajax.Request('/communities/'+community.permalink+"/ideas/live_search", {method: 'post', parameters: "search_string="+this.search_field.value + "&search_value="+search_create})
        }
		    //stop the submit event
		    e.stop()
	  }
})
search = new LiveSearch();
Event.observe(window,'load', search.construct.bindAsEventListener(search))

function mark_selection_for_destroy(element) {
    $(element).next('.should_destroy').value = 1;
    $(element).up('.selection').hide();
}
function remove_option(element){
    $(element).up('.selection').remove();
}

function edit_idea_asset_remove(id) {
    hidden_field = $('destroy_assets');
    remove_link = $('remove_asset_' + id);
    restore_link = $('restore_asset_' + id);
    asset_preview = $('asset_preview_' + id);
    remove_link.hide();
    restore_link.show();
    asset_preview.setStyle({opacity: 0.2})
    hidden_field.value = hidden_field.value + ' ' + id;
}

function edit_idea_asset_restore(id) {
    hidden_field = $('destroy_assets');
    remove_link = $('remove_asset_' + id);
    restore_link = $('restore_asset_' + id);
    asset_preview = $('asset_preview_' + id);
    remove_link.show();
    restore_link.hide();
    asset_preview.setStyle({opacity: 1});
    old_ids = hidden_field.value.match(/[0-9]+/g);
    new_ids = []
    old_ids.each(function(x){if(x != id){new_ids.push(x)}})
        hidden_field.value = new_ids.join(' ')
}

var MatrixCheckArray = {}
MatrixCheckArray = Class.create({
	  check_box: null,
	  check_form: null,
	  construct: function(){
		    //find elements
		    this.check_box = $('check_uncheck_all');		
		    //catch no form
		    if(!this.check_box){return false;}
		    this.check_form = $('check_uncheck_all').up('form');
		    this.check_box.observe('click', this.toggle.bind(this), false);        
	  },
	  toggle:function(e){
		    this.inputs = Form.getInputs(this.check_form, 'checkbox')
		    this.inputs.each(function(el){
			      el.checked = this.check_box.checked
		    }, this)
	          }
});
matrix_select = new MatrixCheckArray();
Event.observe(window,'load', matrix_select.construct.bindAsEventListener(matrix_select))

/* onChange event for Choose Portal select menu on admin pages */
var PortalSelect = {}
PortalSelect = Class.create({
    portal_menu:null,
    initialize: function(){},
    //bind function to onchange event
    watchMenu: function(el_id){ 
        this.portal_menu = $(el_id);
		    if(!this.portal_menu){return;}
		    
        this.portal_menu.observe('change', this.portalMenuChanged.bind(this), false);
    },
    //Take some action when a menu has changed
    portalMenuChanged: function(evt){	
        document.location = "/admin/organizations/"+$(evt.target).value
    }
});
port_select = new PortalSelect();

var MatrixMoveTo = {}
MatrixMoveTo = Class.create({
	  action_id:null, //the action
    menu:null, //the menu
	  f:null, //the form
    initialize: function(){},
    //bind function to onchange event
    watchMenu: function(el_id){ 
		    if(el_id=='move_to_community_id'){this.action_id = "move_to_community"}
		    if(el_id=='move_to_stage_id'){this.action_id = "move_to_stage"}
        if(el_id=='copy_to_community_id'){this.action_id = "copy_to_community"}
        if(el_id=='copy_to_categorygroup_id'){this.action_id = "copy_to_categorygroup"}
        if(el_id=='move_to_categorygroup_id'){this.action_id = "move_to_categorygroup"}
		    if(!this.action_id){return;}
		    
		    //select the element
        this.menu = $(el_id);
		    //then sanity check
		    if(!this.menu){return;}
		    //find the form
		    this.f = this.menu.up('form')
		    //THEN observe
        Event.observe(el_id, 'change', this.menuChanged.bind(this), false);
    },
    //Take some action when a menu has changed
    menuChanged: function(evt){	
        // console.log(this, "changed")
		    
		    //create action type input
		    var el = document.createElement('input');
		    Element.extend(el);
		    el.type = "hidden"
		    el.value = true
		    el.name = this.action_id
		    this.f.appendChild(el)
		    
		    // if your doing a strait submit
		    this.f.submit();
		    
		    //remove this...
		    return false;
    }
});
matrixMoveToCommunity = new MatrixMoveTo();
matrixMoveToStage = new MatrixMoveTo();
matrixCopyToCommunity = new MatrixMoveTo();
matrixCopyToCategorygroup = new MatrixMoveTo();
matrixMoveToCategorygroup = new MatrixMoveTo();

loadme = function(){
    /* onChange event for Choose Portal select menu on admin pages */
    Try.these(function(){port_select.watchMenu('portal_selector');})			
    Try.these(function(){comm_select.watchMenu();})			
    Try.these(function(){matrixMoveToCommunity.watchMenu('move_to_community_id');})			
    Try.these(function(){matrixMoveToStage.watchMenu('move_to_stage_id');})			
    Try.these(function(){matrixCopyToCommunity.watchMenu('copy_to_community_id');})
    Try.these(function(){matrixCopyToCategorygroup.watchMenu('copy_to_categorygroup_id');})			
    Try.these(function(){matrixMoveToCategorygroup.watchMenu('move_to_categorygroup_id');})
};
Event.observe(window, 'load', loadme, false);

var CategoryMoveTo = {}
CategoryMoveTo = Class.create({
	  action_id:null, //the action
    menu:null, //the menu
	  f:null, //the form
    initialize: function(){},
    //bind function to onchange event
    watchMenu: function(el_id){
        if(el_id=='copy_to_category_id'){this.action_id = "copy_to_category"}
        if(el_id=='move_to_category_id'){this.action_id = "move_to_category"}
		    if(!this.action_id){return;}
		    
		    //select the element
        this.menu = $(el_id);
		    //then sanity check
		    if(!this.menu){return;}
		    //find the form
		    this.f = this.menu.up('form')
		    //THEN observe
        Event.observe(el_id, 'change', this.menuChanged.bind(this), false);
    },
    //Take some action when a menu has changed
    menuChanged: function(evt){
        //var can_be_cop_mov = true
        //        if($('idea_search_community').selectedIndex == 0)
        //        {
        var a = this.f;
        var b = this.action_id
        var c = this.menu
        this.inputs = Form.getInputs(a, 'checkbox');                
        var ideas_ids = "";
        this.inputs.each(function(el){
            if (el.checked && el.id != "check_uncheck_all")
            {
                ideas_ids += el.value + ","
            }
        }, this)
            
            var url = $('get_category_url').name;
        new Ajax.Request(url, {
            method: 'get',
            parameters: {idea_ids: ideas_ids,category: this.menu.value},
            onComplete: function(transport) {
                if (transport.responseText == "can_be_cop_mov")
                {
                    var el = document.createElement('input');
                    Element.extend(el);
                    el.type = "hidden"
                    el.value = true
                    el.name = b
                    a.appendChild(el)
                    a.submit();
                }
                else
                {
                    c.selectedIndex = 0;
                }
            }
        });
        // Written in a way such that the 1st selection is checked but that can be changed and the ideas can be moved into another category
        //        }
        //        else //if(can_be_cop_mov == true)
        //        {
        //            var el = document.createElement('input');
        //            Element.extend(el);
        //            el.type = "hidden"
        //            el.value = true
        //            el.name = this.action_id
        //            this.f.appendChild(el)
        //            this.f.submit();
        //        }
        //        else{
        //            //remove this...
        //            
        //            return false;
        //        }
    }
});

matrixCopyToCategory = new CategoryMoveTo();
matrixMoveToCategory = new CategoryMoveTo();

loadmetoo = function(){
    /* onChange event for Choose Portal select menu on admin pages */
    Try.these(function(){matrixCopyToCategory.watchMenu('copy_to_category_id');})
    Try.these(function(){matrixMoveToCategory.watchMenu('move_to_category_id');})
};
Event.observe(window, 'load', loadmetoo, false);


var CommunityMoveTo = {}
CommunityMoveTo = Class.create({
	  action_id:null, //the action
    menu:null, //the menu
	  f:null, //the form
    initialize: function(){},
    //bind function to onchange event
    watchMenu: function(el_id){
        if(el_id=='idea_copy_to_community_id'){this.action_id = "copy_to_community"}
        if(el_id=='idea_move_to_community_id'){this.action_id = "move_to_community"}
		    if(!this.action_id){return;}
		    
		    //select the element
        this.menu = $(el_id);
		    //then sanity check
		    if(!this.menu){return;}
		    //find the form
		    this.f = this.menu.up('form')
		    //THEN observe
        Event.observe(el_id, 'change', this.menuChanged.bind(this), false);
    },
    //Take some action when a menu has changed
    menuChanged: function(evt){
        var a = this.f;
        var b = this.action_id
        var c = this.menu
        this.inputs = Form.getInputs(a, 'checkbox');
        
        var ideas_ids = "";
        this.inputs.each(function(el){
            if (el.checked && el.id != "check_uncheck_all")
            {
                ideas_ids += el.value + ","
            }
        }, this)
            
            var url = $('get_community_url').name;
        new Ajax.Request(url, {
            method: 'get',
            parameters: {idea_ids: ideas_ids,community: this.menu.value},
            onComplete: function(transport) {
                if (transport.responseText == "can_be_cop_mov")
                {
                    var el = document.createElement('input');
                    Element.extend(el);
                    el.type = "hidden"
                    el.value = true
                    el.name = b
                    a.appendChild(el)
                    a.submit();
                }
                else if(transport.responseText == "cannot_be_cop_mov")
                {
                    if(confirm("Some of the copied ideas are associated with categories not available in the target community and will appear as Uncategorized"))
                    {
                        var el = document.createElement('input');
                        Element.extend(el);
                        el.type = "hidden"
                        el.value = true
                        el.name = b
                        a.appendChild(el)
                        a.submit();
                    }
                    else
                    {
                        c.selectedIndex = 0;
                    }
                }
                else
                {
                    c.selectedIndex = 0;
                }
            }
        });
    }
});

matrixIdeaCopyToCommunity = new CommunityMoveTo();
matrixIdeaMoveToCommunity = new CommunityMoveTo();

loadmecommunity = function(){
    /* onChange event for Choose Portal select menu on admin pages */
    Try.these(function(){matrixIdeaCopyToCommunity.watchMenu('idea_copy_to_community_id');})
    Try.these(function(){matrixIdeaMoveToCommunity.watchMenu('idea_move_to_community_id');})
};
Event.observe(window, 'load', loadmecommunity, false);


var BrowseNav = {}
BrowseNav = Class.create({
	  initialize: function(){},
	  construct: function(){
		    this.control = $("browse_control")
		    if(!this.control){return false;}
	      
		    this.b_link = this.control.down("div")
		    this.b_nav = $('browse_links')
	      
		    this.b_link.observe('mouseover', this.toggle_browse.bindAsEventListener(this))
		    this.b_link.observe('mouseout', this.toggle_browse.bindAsEventListener(this))
		    this.b_link.down().observe('click', function(e){e.stop()})
	  },
	  toggle_browse: function(e){
		    this.b_nav.toggle()
	  }	

})
browse_nav = new BrowseNav();
Event.observe(window,'load', browse_nav.construct.bindAsEventListener(browse_nav))

var HistoryNav = {}
HistoryNav = Class.create({
	  initialize: function(){},
	  construct: function(){
		    this.control = $("history_control")
		    if(!this.control){return false;}
	      
		    this.h_link = this.control.down("div")
		    this.h_nav = $('history_links')
	      
		    this.h_link.observe('mouseover', this.toggle_history.bindAsEventListener(this))
		    this.h_link.observe('mouseout', this.toggle_history.bindAsEventListener(this))
	  },
	  toggle_history: function(e){
		    this.h_nav.toggle()
	  }	

})
history_nav = new HistoryNav();
Event.observe(window,'load', history_nav.construct.bindAsEventListener(history_nav))

var CommunitySearch = {}
CommunitySearch = Class.create({
	  initialize: function(){},
	  construct: function(){
		    this.control = $("community_control")
		    if(!this.control){return false;}
	      
		    this.c_link = this.control.down("div a")
		    this.c_form = $('community_form')
	      
		    this.c_link.observe('click', this.toggle_community_form.bindAsEventListener(this))
		    // this.c_link.observe('mouseout', this.toggle_community_form.bindAsEventListener(this))
	  },
	  toggle_community_form: function(e){
		    this.c_form.toggle()
		    e.stop()
	  }	

})
community_search = new CommunitySearch();
Event.observe(window,'load', community_search.construct.bindAsEventListener(community_search))


var CommBrowser = {}
CommBrowser = Class.create({
	  initialize: function(){},
	  construct: function(){
		    this.nav = $('community_sel')
		    if(!this.nav){return}
		    this.nav_open_link = this.nav.down('a') 
		    if(!this.nav_open_link){return}
		    this.close_links = $$('div#community_sel a.comm_nav_close')
		    
		    this.community_menu = $('community_sel');
        this.community_child_menu = $('columnnav');
		    this.menu_container = $('comm_menu_container')
        this.child_menu_objects = $$('div#comm_menu_container div')

		    this.forward_links = $$('div#columnnav a.forward_link')
		    // console.log(this.forward_links)
		    
		    this.back_links = $$('div#columnnav a.back_link')
		    // console.log(this.back_links)
		    
		    this.nav_open_link.observe('click', this.toggle.bindAsEventListener(this), false);
        
		    this.close_links.each(function(link){
			      link.observe("click", this.toggle.bindAsEventListener(this))
		    },this)
		        
		        this.back_links.each(function(link){
			          link.observe("click", this.scrollBack.bindAsEventListener(this))
		        },this)

		            this.forward_links.each(function(link){
			              link.observe("click", this.scrollForward.bindAsEventListener(this))
		            },this)

		                this.hideAll()
	  },
	  toggle: function(e){
		    // console.log("toggling")
		    if(this.is_open){
			      this.community_child_menu.removeClassName('extended').hide();
			      this.hideAll()
			      this.is_open = false;
		    }
		    else{

			      this.community_child_menu.addClassName('extended').show();
			      // console.log('showing', community.permalink)
			      this.showDiv("community_root")
			      this.is_open = true;
		    }	
		    e.stop();	
	  },
	  scrollForward: function(e){
		    link = e.element();
		    to_menu = $("community_"+link.rel.sub('forward_to_', ''))
		    from_menu = e.element().up('div')
		    
		    this.showDiv(to_menu);
		    new Effect.Move(this.menu_container,{x: -350, y: 0, duration: 0.3, mode:'relative', queue: 'front'})
		    new Effect.Move(this.menu_container,{x: 350, y: 0, duration: 0.0, mode:'relative', queue: 'end'})
		    this.hideDiv.delay(0.3, from_menu)
		    
		    e.stop();
	  },
	  scrollBack: function(e){
		    link = e.element();
		    to_menu = $("community_"+link.rel.sub('back_to_', ''))
		    from_menu = e.element().up('div')

		    new Effect.Move(this.menu_container,{x: -350, y: 0, duration: 0.0 , mode:'relative', queue: 'front'})
		    this.showDiv(to_menu);
		    // new Effect.Move(this.menu_container,{x: 350, y: 0, duration: 0.3 , mode:'relative', queue: 'front'})
		    new Effect.Move(this.menu_container,{x: 350, y: 0, duration: 0.3 , mode:'relative', queue: 'end'})
		    
		    this.hideDiv.delay(0.3,from_menu)
		    e.stop();
	  },
	  showDiv: function(menu){
        if($(menu)){
		        $(menu).show();
        }
	  },
	  hideDiv: function(menu){
		    menu.hide();
	  },
	  hideAll: function(){
		    this.child_menu_objects.each(function(menu){
			      menu.hide();
		    })
	          }
})
comm_browser = new CommBrowser();
Event.observe(window,'load', comm_browser.construct.bindAsEventListener(comm_browser))


function mark_default_stage(id) {
    $$('.toggle_default').each(function(x){
        x.checked = false;
    });
    $('toggle_default_stage_' + id).checked = true;  
    return false;
}

function init_login_link(link){
	  link.href='/login'
}


function init_error_link(link,request_url){
    link.href=request_url;
}

function admin_cancel_new_field() {
    $('new_field').innerHTML = '<!-- -->';
}

var IdeaStageFilter = {}
IdeaStageFilter = Class.create({
	  initialize: function(){},
	  construct: function(){
		    this.menu = $("idea_stage_filter")
		    if(!this.menu){return}
		    this.menu.observe("change", this.changeaction.bindAsEventListener(this))
	  },
	  changeaction: function(e){
		    document.location="?stage="+this.menu.value
	  }
})
idea_stage_filter = new IdeaStageFilter();
Event.observe(window,'load', idea_stage_filter.construct.bindAsEventListener(idea_stage_filter))


function _clearfield(e, d){
    if (e.value == d){
        e.value = '';
    }
}

function regen_sso_key(key_area){
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
    var string_length = 32;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    $(key_area).value = randomstring;
}

function clear_sso_key(){
    $('organization_sso_key').value = ''; 

}

/*  
    This function will set the value to hidden field while creating and editing ideas. There are 3 buttons
	  while creating idea so value should be set to hidden field  after perticular button has been clicked

*/
function set_idea_create_btn_value(element, value){
    $(element).value=value;
}

function check_url()
{
    if (history.length == 1){
        document.location.href = "/";        
    }
    else{
        history.back();        
    }
}

function number_of_selected_communities()
{
    var inputs = Form.getInputs($('check_uncheck_all').up('form'), 'checkbox');      
    var count = 0;

    for(i=0 ;i< inputs.size();i++)
    {
        if (inputs[i].checked)
        {
            count++;
        }                        
    } 
    
    if (count == 0)
    {
        alert("Please select at least one community");
        return false;
    }
    else if (count == 1)
    {
        return confirm("Are you sure you want to delete this community?");
    }
    else
    {
        return confirm("Are you sure you want to delete these communities?");
    }
}

function slide_down(parent_id, child_id,depth)
{
    var state = $(child_id).style.display;
    var div_columnnav = $("columnnav");         
    var base_width=0;
    if ( (navigator.appVersion).indexOf("MSIE 6.0"))
        base_width=500;
    else
        base_width=400;
    
    var increase_width = 30;
    if (div_columnnav.style.width == '' || div_columnnav.style.width==null)
    {
        div_columnnav.style.width = base_width+'px';             
    }
    
    if (state == "block")
    {
        $(child_id).style.display = "none";
        $(parent_id).className = "slide_ul";
        if((parseInt(div_columnnav.style.width.replace('px',''))-(base_width + increase_width*depth)) == increase_width)
            div_columnnav.style.width = (base_width + increase_width*depth) + "px";
        
    }
    else{
        $(child_id).style.display = "block";  
        $(parent_id).className = "slide_down_ul";
        if((base_width + increase_width*depth)-(parseInt(div_columnnav.style.width.replace('px','')))==increase_width)
            div_columnnav.style.width = (base_width + increase_width*depth) + "px";
    }      
}


Event.observe(window,'load',function(){

    if(!window.location.href.match(/\/login/) && document.getElementsByClassName('flash_notice')[0] && document.getElementsByClassName('flash_notice')[0].innerHTML.match(/do not have permission/))
	      show_access_denied_msg(document.getElementsByClassName('flash_notice')[0].innerHTML);
});

/*  Show alert message for Access denied */
function show_access_denied_msg(msg){
    alert(msg);
}

Event.observe(window,'load',function(){
    Event.observe($("powered_by"), 'click',function(){
        window.open("http://www.acceptsoftware.com/", "_blank"); done=1;
    });
});

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		$(limitCount).innerHTML = "Characters remaining : " + (limitNum - limitField.value.length);
	}
}
