var extra = new Object();
extra.add = function( group , struct ){
    var data = new Array();
    var k = 0;
    for (var key in struct ) {
        if ( struct.hasOwnProperty( key ) ) {
            if( ( typeof struct[ key ] ).toString() != "string" ){
                for( var i = 0; i < struct[ key ].length; i++ ){ //alert(extra.val( key + '#' + struct[ key ][i] ) +' __ '+jQuery(key + '#' + struct[ key ][i]).val());
                    data[ k ] = { 'name' : jQuery( key + '#' + struct[ key ][i] ).attr( 'name' ) , 'value' : jQuery(key + '#' + struct[ key ][i]).val() }

                    k++;
                }
            }else{
                data[ k ] = { 'name' : extra.name( key + '#' + struct[ key ] ) , 'value' : extra.val( key + '#' + struct[ key ] ) }
                k++;
            }
        }
    }


    jQuery( document ).ready(function(){
        jQuery.post( 
            ajaxurl , { "action" : 'extra_add' , 
                        "group" : group , 
                        "data" : data
                    } , 
            function( result ){ 
                //extra.clear( struct ); 
                //jQuery( '#container_' + group  ).html( result ); 
                var modiffied_result = '<html><head></head>'+result+'</html>'; /*insert the result inside a valid HTML to be able to get only the updated row*/
                var updated_form = jQuery(modiffied_result).find('.form_holder').html(); /*get only the updated form*/
                jQuery('.form_holder').html(updated_form);
                hide_non_related_content_menu_settings(); /*for each object type - hide non related settings*/
                reinit_stuf(); /*init color picker and slider*/
            } 
        );
    });
}


extra.del = function( group , index ){
    if(  confirm('You sure you want to delete this item from group ?') ){
        jQuery( document ).ready(function(){
            jQuery.post( ajaxurl , { "action" : 'extra_del' , "group" : group , "index" : index } , function( data ){
                 

                json = eval("(" + data + ")");
            
                //jQuery( '#container_' + group  ).html( json['content'] );

                var modiffied_result = '<html><head></head>'+json['content']+'</html>'; /*insert the result inside a valid HTML to be able to get only the updated row*/
                var updated_form = jQuery(modiffied_result).find('.form_holder').html(); /*get only the updated form*/
                jQuery('.form_holder').html(updated_form);
                hide_non_related_content_menu_settings(); /*for each object type - hide non related settings*/
                // if(json['clear_default_selected_menu'] && json['clear_default_selected_menu'] != ''){
                //     jQuery(json['clear_default_selected_menu']).val(''); //clear the value for the input that holds  default_selected_menu 
                // }
                

            } );
        });
    }
}

extra.update = function( group , index , struct ){
    var data = new Array();
    var k = 0;
    for (var key in struct ) {
        if ( struct.hasOwnProperty( key ) ) {
            if( ( typeof struct[ key ] ).toString() != "string" ){ 
                for( var i = 0; i < struct[ key ].length; i++ ){ 
                    data[ k ] = { 'name' : extra.name( 'div#multiple_record_' + group + '_' + index + ' ' + key + '.' + struct[ key ][i] ) , 'value' : extra.val( 'div#multiple_record_' + group + '_' + index + ' ' + key + '.' + struct[ key ][i] ) }
                    k++;
                }
            }else{ 
                data[ k ] = { 'name' : extra.name( 'div#multiple_record_' + group + '_' + index + ' ' + key + '.' + struct[ key ] ) , 'value' : extra.val( 'div#multiple_record_' + group + '_' + index + ' ' + key + '.' + struct[ key ] ) }
                k++;
            }
        }
    }

    jQuery( document ).ready(function(){
        jQuery.post( ajaxurl , { 
            "action" : 'extra_update' , 
            "group" : group , 
            "index": index , 
            "data" : data } , 
            function( result ){ 
                /* result received reprresents the entire form */

                // jQuery( '#container_' + group  ).html( result ); 
                
                //var modiffied_result = '<html><head></head>'+result+'</html>'; /*insert the result inside a valid HTML to be able to get only the updated row*/
                //var updated_form = jQuery(modiffied_result).find('#serial_multiple_record__content_menu').html(); /*get only the updated form*/
                //console.log( jQuery(modiffied_result).find('#multiple_record_'+group+'_'+index).html());
                //jQuery('#multiple_record_'+group+'_'+index).html( updated_row );
                //jQuery('#serial_multiple_record__content_menu').html(updated_form);

                var modiffied_result = '<html><head></head>'+result+'</html>'; /*insert the result inside a valid HTML to be able to get only the updated row*/
                var updated_form = jQuery(modiffied_result).find('.form_holder').html(); /*get only the updated form*/
                jQuery('.form_holder').html(updated_form);
                hide_non_related_content_menu_settings(); /*for each object type - hide non related settings*/
                reinit_stuf(); /*init color picker and slider*/
                
                if(group == '_content_menu'){
                    showMsg('.init_menu_save_msg');
                }
            } );
    });
}

extra.edite = function( group , index ){
    jQuery( document ).ready(function(){
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .edit-action').hide();
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .update-action').show();
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .fvisible' ).show();
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .lvisible' ).hide();

        jQuery( 'div#multiple_record_' + group + '_' + index + ' .close_box-action').css('display','inline-block').show();
    });
}

extra.close_box = function( group , index ){
    jQuery( document ).ready(function(){
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .edit-action').show(); /*show edit button*/
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .close_box-action').hide(); /*hide close button*/
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .fvisible' ).hide(); /*hide options inputs*/
        jQuery('input[type="button"].update-action').hide(); /*hide update button*/
        jQuery( 'div#multiple_record_' + group + '_' + index + ' .lvisible' ).show();
    });
}

extra.clear = function( struct ){
	jQuery( document ).ready(function(){
		for (var key in struct ) {
			if ( struct.hasOwnProperty( key ) ) {
				if( ( typeof struct[ key ] ).toString() != "string" ){
					for( var i = 0; i < struct[ key ].length; i++ ){
						jQuery( key + '#' + struct[ key ][i] ).val('');
					}
				}else{
					jQuery( key + '#' + struct[ key ] ).val('');
				}
			}
		}
	});
}
extra.name = function( selector ){
	var name = '';
	jQuery( document ).ready(function(){
		name = jQuery( selector ).attr( 'name' );
	});
	return name;
}
extra.val = function( selector ){
    var result = '';
    jQuery(document).ready(function(){
        if( jQuery( selector ).attr('type') == 'checkbox' || jQuery( selector ).attr('type') == 'radio' ){
            if( jQuery( selector ).is(':checked') ){
                result = jQuery( selector ).val();
            }else{
                result = '';
            }
        }else{
            result = jQuery( selector ).val();
        }
    });
    
    return result;
}


extra.sort = function( group , name, callback ){
    if(typeof(callback)==='undefined') callback = ''; /*if this parameter is not passed*/
   

    var data = new Array();
    jQuery( document ).ready(function(){
        jQuery( 'input.' + group + '.index' ).each(function( i ){
            if(group == '_content_menu' ){ /*for content menu we have menu_depth parameter*/
                if( jQuery(this).parent().parent().find('input.menu_item_depth').val().length ){ 
                    var menu_depth = jQuery(this).parent().parent().find('input.menu_item_depth').val();
                }else{
                    var menu_depth = 0;
                }
                data[i] = { 'name' : name , 'value' : jQuery(this).val(), 'menu_item_depth' : menu_depth };
            }else{
                data[i] = { 'name' : name , 'value' : jQuery(this).val() };
            }
            
        });

        jQuery.post( ajaxurl , { "action" : "extra_sort" , "group" : group , "data" : data } ,
            function( result ){
                /*we don't need to show the content again, this only puts load on the browser*/
                //jQuery( '#container_' + group ).html( result );

                var modiffied_result = '<html><head></head>'+result+'</html>'; /*insert the result inside a valid HTML to be able to get only the updated row*/
                var updated_form = jQuery(modiffied_result).find('.form_holder').html(); /*get only the updated form*/
                jQuery('.form_holder').html(updated_form);
                hide_non_related_content_menu_settings(); /*for each object type - hide non related settings*/
                reinit_stuf(); /*init color picker and slider*/
                
                /*if callback code is passed*/
                if(callback.length){ 
                    eval(callback);
                }
            }
        );
    });
}


function init_ui_slider(obj_selector){
    jQuery(obj_selector).each(function (i) {
        jQuery(this).slider({
             range: "min",
             min: jQuery(this).data('min'),
             max: jQuery(this).data('max'),
             value: jQuery(this).data('val') ,
             slide: function (event, ui) {
                jQuery(this).next('span.slider_val').text(ui.value);
                jQuery(this).prev('.slider_value').val(ui.value);
             },
             
             change: function (event, ui) {

             }
        });
    });
}


/*used for content_menu to hine options that are not related to a given Object type*/
function hide_non_related_content_menu_settings(){
    
    var object_types = ['category','post_tag', 'portfolio-category', 'portfolio-tag','box-sets','team-group',  'testimonial-category',  'page', 'post',  'slideshow', 'external_link'  ];
    
    
    /*add here the element classes you want to hide (usualy it is the input  class, we will hide the parent and label for this input) */
    var category_object_type = [ '.delimiter4', '.open_in_new_tab', '.external_link','.filter_by', '.enable_filter','.slide_transition', '.auto_play',  '.delimiter3','.content_background_color','.bg_color_opacity', '.content_number_of_columns']; 
    var post_tag_object_type = category_object_type;
    var portfolio_category_object_type = category_object_type;
    var portfolio_tag_object_type = category_object_type;
    var post_format_object_type = [ '.delimiter4', '.open_in_new_tab', '.external_link','.slide_transition', '.auto_play',  '.delimiter3','.content_background_color','.bg_color_opacity', '.content_number_of_columns']; 
    var box_sets_object_type = [ '.delimiter4', '.open_in_new_tab', '.external_link','enable_filter', 'filter_by','.slide_transition',  '.auto_play',  '.delimiter3', '.post_background_color', '.post_background_color_opacity', '.content_view_type','.content_resize_method','.enable_load_more', '.enable_ajax_post', '.open_mode', '.content-menu-order-by','.content-menu-order'];
    var team_group_object_type = [ '.delimiter4', '.open_in_new_tab', '.external_link','enable_filter', 'filter_by','.slide_transition', '.auto_play', '.delimiter3','.enable_masonry ',  '.post_background_color', '.post_background_color_opacity', '.content_view_type','.content_resize_method','.enable_load_more', '.enable_ajax_post', '.open_mode', '.content-menu-order-by','.content-menu-order'];
    var testimonial_category_object_type = [ '.delimiter4', '.open_in_new_tab', '.external_link','enable_filter', 'filter_by','.slide_transition', '.auto_play', '.delimiter3', '.content_number_of_columns', '.enable_masonry ', '.post_background_color', '.post_background_color_opacity', '.content_view_type','.content_resize_method','.enable_load_more', '.enable_ajax_post', '.open_mode', '.content-menu-order-by','.content-menu-order'];
    var page_object_type = [ '.delimiter4', '.open_in_new_tab', '.external_link','enable_filter', 'filter_by','.slide_transition', '.post_background_color','.auto_play', '.delimiter3', '.post_background_color_opacity' ,'.digit', /*'.color_picker_text', '.color_picker', */ '.enable_masonry ', '.content_number_columns', '.content_number_of_columns' , '.content_view_type','.content_resize_method','.enable_load_more', '.enable_ajax_post', '.open_mode', '.content-menu-order-by','.content-menu-order'];
    var post_object_type = page_object_type;
    var portfolio_object_type = page_object_type;
    var slideshow_object_type = ['.delimiter4', '.open_in_new_tab', '.external_link', 'enable_filter', 'filter_by','.enable_masonry', '.content_number_columns', '.content_number_of_columns', '.digit', '.delimiter6', '.delimiter2', '.delimiter1', '.color_picker', '.background_color', '.post_background_color', '.post_background_color_opacity', '.background_image', '.bg_object', '.content_background_color','.bg_color_opacity', '.color_picker_text','.content_view_type','.content_resize_method','.enable_load_more', '.use_gutter', '.enable_ajax_post', '.open_mode', '.content-menu-order-by','.content-menu-order'];
    var external_link_object_type = ['.delimiter3','.toggle_style','.enable_filter', '.filter_by','.enable_masonry', '.content_number_columns', '.content_number_of_columns', '.digit', '.delimiter6', '.delimiter2', '.delimiter1', '.color_picker', '.background_color', '.post_background_color', '.post_background_color_opacity', '.background_image', '.bg_object', '.content_background_color','.bg_color_opacity', '.color_picker_text','.content_view_type','.content_resize_method','.enable_load_more', '.use_gutter', '.enable_ajax_post', '.open_mode', '.content-menu-order-by','.content-menu-order'];

    /*iterate through sortable rows that have class  multiple-record-_content_menu*/
    jQuery('.multiple-record-_content_menu').each(function (i) { 
        var row = jQuery(this);
        var obj_type = row.attr('object_type'); /*each _content_menu row has an attribute 'object_type' */

        var exact_class = ['.delimiter6','.delimiter2', '.delimiter1', '.delimiter3', '.delimiter4', '.toggle_style'];
        /*eval(obj_type + '_object_type')  -  uses the Object_type atribute to determine which arrays from above must be used for the current row */

        jQuery.each( eval(obj_type + '_object_type') , function(index,value) {  
            /*get the element that has given ID, then we get Parent with class .fvisible, and hide children with classes '.label, .input' */
            row.find(value).parents('.fvisible').find('.label, label, .input').hide();

            if(jQuery.inArray( value, exact_class) > -1){
                row.find(value).hide();
            }
            //if(value =='.delimiter1'){ row.find(value).hide(); }
        });
    
        
    });

    /*here we will hide elements that deppend on more than 1 option*/

    jQuery('.multiple-record.multiple-record-_content_menu').each(function(index) {
        var menu_id = jQuery(this).find('input.idrow.index._content_menu').val();
        var view_type = jQuery('#_content_menu_view_type'+menu_id).val();
        if(jQuery('#_content_menu_enable_filter'+menu_id).is(':checked')) {
            var enb_filter = true;
        }else{
            var enb_filter = false;
        }

        if(view_type == 'thumb_view' && enb_filter){ 
            /*hide masonry, load more */

            jQuery('#_content_menu_enable_masonry'+menu_id).hide(); jQuery('#_content_menu_enable_masonry'+menu_id+'_title').hide(); jQuery('#_content_menu_enable_masonry'+menu_id+'_hint').hide(); 
            jQuery('#_content_menu_enable_load_more'+menu_id).hide(); jQuery('#_content_menu_enable_load_more'+menu_id+'_title').hide(); jQuery('#_content_menu_enable_load_more'+menu_id+'_hint').hide();
        }

        /* open post via ajax dependency */
        if( jQuery('#_content_menu_enable_ajax_post'+menu_id).is(':checked')){
            var enb_ajax = true;
        }else{
            var enb_ajax = false;
        } 
        if(!enb_ajax){
            jQuery('#_content_menu_open_mode'+menu_id).hide(); jQuery('#_content_menu_open_mode'+menu_id+'_title').hide();
        }

    });
    jQuery('#_content_menu_type').change(function () {       
        if(jQuery("#_content_menu_type option:selected").val() == 'external_link') {
            jQuery('.external_link_save').removeClass('hidden');
        } else {
            jQuery('.external_link_save').addClass('hidden');
        }
    });
    jQuery('.generic-field-_content_menu.external_link_save .button-primary').click(function () { 
        jQuery('.generic-field-_content_menu.external_link_save').addClass('hidden');
        jQuery('.standard-generic-field.generic-field-_content_menu.external_link #external_link').val(""); 
        jQuery('.standard-generic-field.generic-field-_content_menu.external_link').hide(); 
        jQuery('select.generic-_content_menu').prop('selectedIndex',0);
        showMsg('.row_added_msg');
    });   
    
}

jQuery(document).ready(function(){
    jQuery('span.icon-container').live('click',function(){
        //show hide the div containing the icons for the menu
        jQuery(this).parent().find('div.icon-container').toggle();
    });

    jQuery('.menu_icons_box  input[type="radio"]').live('change',function(){
        //when a menu icon is selected we store it's value in a hidden input
        if(jQuery(this).is(':checked')){
            jQuery('#'+jQuery(this).data('id')).val(jQuery(this).val());
        }
    });

    jQuery('[name="menu_icon123"]').live("click",  function(event){
        jQuery(this).parents('div.input.menu_icon').find('.the_current_val').html('<i class="'+jQuery(this).val()+'"></i>');
        jQuery(this).parents('div.icon-container.hidden').hide();
    });


    /*jQuery('[name="menu_icon123"]').on('click'){
        jQuery(this).parent().find('.the_current_val').val(jQuery(this).val());
    }*/
});

function get_sort_elem_class(ui){
    
    if(ui.item.index() == 0){ /* if the element is placed in the first row we force it to 0 depth */
        var adjusted_depth = 0;
        var sort_elem_class = 'menu_item_depth_'+adjusted_depth; 
        //ui.item.attr('data-depth',adjusted_depth); /*update the depth data*/ 
        //jQuery('#multiple_record__content_menu_'+ui.item.index()).attr('data-depth',adjusted_depth);
        ui.item.attr('data-depth',adjusted_depth);
        ui.item.find('input.menu_item_depth').val(adjusted_depth);
        //console.log('#multiple_record__content_menu_'+ui.item.index());
    }else{
        var left_pos = ui.position.left; /*how much pixels the element was moved horizontally - may have positive or negative value*/
        
        var step = 60; /*the visual displacement between different menu depth levels*/
        var current_depth = ui.item.attr('data-depth'); /*get current element depth storred in data-depth*/
        var depth =  parseInt(current_depth) + Math.floor( left_pos/step); /* current depth + how much the element was moved(rounded down to the closest 'step')*/


        if(depth < 0 ){ 
            var adjusted_depth = 0; /*if user moved the element too far to the left we set it to depth = 0*/
        }else{ 
            
            /*check the depth of the element above the current one*/
            var prev_elem_id = 'multiple_record__content_menu_' + parseInt(ui.item.index() - 1);
            var prev_elem_depth = jQuery('#'+prev_elem_id).attr('data-depth'); 

        
            
            if( parseInt(depth - prev_elem_depth) > 1){ /*if the element is dragged too far to the right */ 
                var adjusted_depth = parseInt(prev_elem_depth) + 1;     /*force the depth to be + 1 unit compared to the element above*/
            }else{
                var adjusted_depth = depth;     
            }
            
        }

        //ui.item.data('depth',adjusted_depth); /*update the depth data*/
        //jQuery('#multiple_record__content_menu_'+ui.item.index()).attr('data-depth',adjusted_depth);
        ui.item.attr('data-depth',adjusted_depth);
        ui.item.find('input.menu_item_depth').val(adjusted_depth);
        var sort_elem_class = 'menu_item_depth_'+adjusted_depth; 
        
    }
    
    var classes_to_remove = 'menu_item_depth_0 menu_item_depth_1 menu_item_depth_2 menu_item_depth_3 menu_item_depth_4 menu_item_depth_5 menu_item_depth_6 menu_item_depth_7 menu_item_depth_8 menu_item_depth_9 menu_item_depth_10 menu_item_depth_11 menu_item_depth_12 menu_item_depth_13 menu_item_depth_14 '; /*I think it is enough*/
    ui.item.removeClass(classes_to_remove).addClass(sort_elem_class); /*update the depth class*/
   
}

function adjust_rows_data(ui, group){
    var i = 0;

    /*iterate through each row*/
    jQuery('div.multiple-record-'+group).each(function(index){
        
        if( typeof(jQuery(this).find('.idrow.index.'+group).val()) != 'undefined' ){
            jQuery(this).find('.idrow.index.'+group).val(i); /*update the value of the hidden input*/
            jQuery(this).attr('id','multiple_record_'+group+'_'+i); /*update the ID of the current row*/
            jQuery(this).find('.idrow.index.'+group).attr('id',group+'_idrow'+i); /*update the ID of the hidden row*/
            i++;
        }
        
    });
}

function toggle_styling_container(obj){ 
    var icon = obj.find('i');
    
    obj.parent().parent().next('.toggle_style').find('div.style_settings_container').fadeToggle("fast", "linear", function(){
        //console.log(jQuery(this).attr('class'));
        if(icon.hasClass('icon-caret-down')){
            icon.removeClass('icon-caret-down').addClass('icon-caret-up');
        }else{
            icon.removeClass('icon-caret-up').addClass('icon-caret-down');    
        }
    });

}

function change_checkbox_elem(obj,affected_elements,method){
    /*  affected_elements are available as a strin separated by comma in this form:
        '#_content_menu_enable_masonry0 , #_content_menu_enable_masonry0_title , #_content_menu_enable_masonry0_input_content   , #_content_menu_filter_by0 , #_content_menu_filter_by0_title , #_content_menu_filter_by0_input_content   , #_content_menu_enable_load_more0 , #_content_menu_enable_load_more0_title , #_content_menu_enable_load_more0_input_content  '

        we want to split the string by comma and create a array
    */
    var elements = affected_elements.split(','); /**/


    if(obj.is(':checked')) {
        jQuery.each(elements, function(key, value) {  //console.log(value);
            var elem_id = jQuery.trim(value).replace("#","");
            if(method == 'sh'){
                jQuery("#"+elem_id).show();  
            }else{
                jQuery("#"+elem_id).hide();  
            }
            
        });    
    }else{
        jQuery.each(elements, function(key, value) { 
            var elem_id = jQuery.trim(value).replace("#","");

            if(method == 'sh'){
                jQuery("#"+elem_id).hide();  
            }else{
                jQuery("#"+elem_id).show();  
            }
            
        });   
    }
}

function reinit_stuf(){
    var color_picker_classes = ['post_background_color','color_picker_text', 'content_background_color','color_picker'];
    jQuery.each(color_picker_classes, function(key, value) {
        init_color_pickers('input.'+value );    
    });

    init_ui_slider('.ui_slider');
    
}