var timeout_id;
var counter;
var progress_timeout_id;
$(document).ready(function(){

    if($('form.ajax_data').get(0)) {
        $('form.ajax_data').each(function(){
            init_ajax_data_form(this);
        })
    }
    $.collapsible(".module .header");

    bindAssignProfilesTo();

  $('.attachment_link').imgPreview({
         onLoad:function(){
            var max = 400;
            if (this.width > max) {
                $(this).css({width: '400px', height: 'auto'});
            }else if (this.height > max){
                $(this).css({width: 'auto', height: '400px'});
            }           
        }
        }
    );
        $('#log_form .check_all').click(function(){
                if($(this).hasClass('checked')){
                        $('#log_form input[type=checkbox]').removeAttr('checked');
                        $(this).removeClass('checked');
                } else {
                        $('#log_form input[type=checkbox]').attr('checked',true);
                        $(this).addClass('checked');
                }
        });
        $('#log_form .submit_form').click(function(){
            var items_selected = $('#log_form input[type=checkbox]:checkbox:checked').length;
            if(items_selected == 0){
                    alert('Please select items first.');
                    return false;
            }
            else
            {
                var action_up = $('#action_up').val();
                var action_down = $('#action_down').val();
                if (action_up == '' && action_down == '')
                {
                    alert('Please select what to do with selected items.');
                    return false;
                }
            }
         
        });
	if($('#db_file_update').get(0)){
		var error = '';
		$('#db_file_update').submit(function(){
			var checked_cols = $('input.display_columns[checked]').length;
			var drag_scan = $('#dragged_SCANBOX').get(0);
			if(!drag_scan){
				error += "Please drag scanbox to one of columns from your lookup file\n";
			} 
			if(checked_cols == 0){
				error += "You should check columns that you want to display in result file\n";
			} else if (checked_cols == 1 && !error){
				var col = $('input.display_columns[checked]').get(0);
				if($(col).attr('name') == 'display_columns['+$('#dragged_SCANBOX').val()+']'){
					error += "You should check columns that you want to display in result file except mapping column\n";
				}
			}
			if(error){
				alert(error);
				error = '';
				return false;
			}
			return true;
		})
	}

    if($('#convet_db_file').get(0)){
		$('#convet_db_file').submit(function(){
                    var descriptionMap = $('#dragged_DescriptionMap').get(0);
                    if (descriptionMap ){
                        var itemMap = $('#dragged_ItemIDMap').get(0);
                        var upcMap = $('#dragged_UPCMap').get(0);
                        if (!itemMap && !upcMap){
                            alert('You should map ItemID or UPC column. You can also upload the file without using FTS.');
                            return false;
                        }
                    }

            return true;
		})
	}
        
    if($('#convet_file').get(0)){
		$('#convet_file').submit(function(){
                    var checkInMap = $('#CheckInMap').get(0);
                    if (checkInMap){

                        var dragged_ScanCodeMap = $('#dragged_ScanCodeMap').get(0);
                         if (!dragged_ScanCodeMap){
                                alert('You should Scan-Code column.');
                                return false;
                         }
                         var dragged_CheckInMap = $('#dragged_CheckInMap').get(0);
                         if (!dragged_CheckInMap){
                                alert('You must map Check-in column.\r\n Please add column to your file for check-in values');
                                return false;
                         }
                    }else{
                         var itemFilesOnly = $('#item_files_only').get(0);

                         if (!itemFilesOnly){
//                            var itemMap = $('#dragged_ItemIDMap').get(0);
//                              if (!itemMap){
//                                    alert('You should map Item ID column.');
//                                    return false;
//                             }

                        var descriptionMap = $('#dragged_DescriptionMap').get(0);
                         if (!descriptionMap){
                                alert('You should map Descrition column.');
                                return false;
                    }
                    }

                        var upcMap = $('#dragged_UPCMap').get(0);
                          if (!upcMap){
                                alert('You should map Scan-Code column.');
                                return false;
                         }                       
                    }

            return true;
		})
	}  
	
        

         if($('#submit_item').get(0)){
		$('#submit_item').submit(function(){

                    var uploadedFile = $('#uploadfile').val();
                    if (uploadedFile == ''){
                        alert('Please choose a file!');
                        return false;
                    }

                   var selectedValue = $('#multi_database_action_select').val();
                   if (selectedValue == 1){
                        var url_name = $('#url_name');
                        var url = url_name.val();
                        if (url == ''){
                            alert('Please specified url.');
                            return false;
                        }

                        if(!/^(https?|ftp):\/\//i.test(url)) {
                            url = 'http://'+url;
                            url_name.val(url);
                        }

                        if (!checkURL(url)){
                            alert('Please specified valid url.');
                            return false;
                        }
                    }

                    return true;
		})
	}
	
	if($('#scannersn_tr').get(0)) {
		$('#group_chk').click(function(){
			if($(this).attr('checked')) {
				$('#scannersn_tr').fadeIn(300);
			} else {
				$('#scannersn_tr').fadeOut(300);
			}
		})
	}	
	if($('#add_drag').get(0)){
		$('#add_drag').unbind('click');
		$('#add_drag').click(function(){
			var box_count = $('#dropContent div.dragableBox').length;
			var box_val = $.trim($('#add_to_drag').val());
			var box_name = $.trim($('#add_to_drag option[value="'+box_val+'"]').html());
			if(box_name){
				$('<div class="dragableBox" id="'+box_val+'">'+box_name+'</div>').appendTo('#dropContent');
				$('#add_to_drag option[value="'+box_val+'"]').remove();
				dragDropObj.addSource(box_val,true);
				dragDropObj.init();
			}
			
		})
	}
	
// Comment to let reassign mapping
//	if($('.ui-sort-container').get(0)){
//		$(".ui-sort-container").sortable({
//		        connectWith: '.ui-sort-container',
//		        items: 'div.dragableBoxRight'
//		    });
//	}

     if($('#file_type').get(0)){
        $('#file_type').change(function(){
            var jThis = $(this);
            var selectValue = jThis.val();
            if (selectValue == 1){
               $('#without_fts').removeAttr('checked');
               return;
            }else if (selectValue == 2){
               $('#without_fts').attr('checked','checked');
            }
        })
    }

    if($('#assign_cust_action_select').get(0)){
        $('#assign_cust_action_select').change(function(){
            var jThis = $(this);
            var selectValue = jThis.val();
            if (selectValue == 0){
               $('#setfilenamerow').attr('style','display:none;');
               $('#saverow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
               $('#choosefilerow').attr('style','display:none;');
               return;
            }else if (selectValue == 1){
               $('#setfilenamerow').attr('style','display:table-row;');
               $('#saverow').attr('style','display:table-row;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
               $('#choosefilerow').attr('style','display:none;');
            }else if (selectValue == 2){
               $('#setfilenamerow').attr('style','display:none;');
               $('#saverow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:table-row;');
               $('#submitrow').attr('style','display:table-row;');
               $('#choosefilerow').attr('style','display:none;');
            }else if (selectValue == 3){
               $('#setfilenamerow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
               $('#choosefilerow').attr('style','display:table-row;');
               $('#saverow').attr('style','display:table-row;');
            }            
        })
    }
	
     if($('#item_action_select').get(0)){
        $('#item_action_select').change(function(){
            var jThis = $(this);
            var selectValue = jThis.val();
            if (selectValue == 0){
               $('#setfilenamerow').attr('style','display:none;');
               $('#saverow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
               return;
            }else if (selectValue == 1){
               $('#setfilenamerow').attr('style','display:table-row;');
               $('#saverow').attr('style','display:table-row;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
            }else if (selectValue == 2){
               $('#setfilenamerow').attr('style','display:none;');
               $('#saverow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:table-row;');
               $('#submitrow').attr('style','display:table-row;');
            }
        })
    }

     if($('#multi_database_action_select').get(0)){
        $('#multi_database_action_select').change(function(){
            var jThis = $(this);
            var selectValue = jThis.val();
            if (selectValue == 0){
               $('#saverow').attr('style','display:none;');
               $('#seturlnamerow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
            }else if (selectValue == 1){
               $('#saverow').attr('style','display:table-row;');
               $('#seturlnamerow').attr('style','display:table-row;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
            }else if (selectValue == 2){
               $('#saverow').attr('style','display:none;');
               $('#seturlnamerow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:table-row;');
               $('#submitrow').attr('style','display:table-row;');
            }
        })
    }
	
	if($('#delivery_format_select').get(0)){
		$('#delivery_format_select').change(function(){
			if($(this).val() == 'HTML'){
				$('tr.html_parts').attr('style','display:table-row;');
				$('tr.xls_parts').attr('style','display:none;');
				$('tr.csv_parts').attr('style','display:none;');
			} else if($(this).val() == 'XLS') {
				$('tr.html_parts').attr('style','display:none;');
				$('tr.xls_parts').attr('style','display:table-row;');
				$('tr.csv_parts').attr('style','display:none;');
			} else if ($(this).val() == 'CSV'){
			    $('tr.html_parts').attr('style','display:none;');
			    $('tr.xls_parts').attr('style','display:none;');
			    $('tr.csv_parts').attr('style','display:table-row;');
                $('#csv_col_sep').attr("disabled", "");
			} else if ($(this).val() == 'TXT'){
			    $('tr.html_parts').attr('style','display:none;');
			    $('tr.xls_parts').attr('style','display:none;');
			    $('tr.csv_parts').attr('style','display:table-row;');
			    /*
			     $('#csv_col_sep').val("2");
			     $('#csv_col_sep').attr("disabled", "disabled");
			     */
			}
		})
	}
	if($('#timer').get(0)){
		close_window();
	}
	if($('a.file_selected').get(0)){
	    $('a.file_selected').click(function(){
	        return confirm('This file is currently used to Perform List Lookup. If you remove this file Perform List Lookup will be disabled. Are you sure you want to do this?');
	    })
	}
	
	if($('a.process').get(0)){
	    $('a.process').click(function(){
	        $.post(
                $(this).attr('href'),
                {'action':'process',
                 'file_id':$(this).attr('rel')},
                function (resp) {
                    if(resp.error){
                        alert(resp.msg);
                        clearTimeout(timeout_id);
                    }
                    window.location.href=window.location.href;
                },
                'json'
	        )
	        $('div.progress').slideDown(200);
	        setTimeout("show_geo_status('"+$(this).attr('href')+"',"+$(this).attr('rel')+")",2000);
	        return false;
	    })
	}

        if($('#ftp_update_data').get(0)){
	    $('#ftp_update_data').click(function(){

                var map = $('#map');
                if (map.val() == 0){
                    var answer = confirm("Item's mapping is not set. Continue?");
                    if (!answer){
                        return false;
                    }
                }

               $.post(
                site_url+'db.php',
                {'action':'generate_id'},
                function (resp) {
                    //alert(resp);
                    $('#progress_id').val(resp);
                }
	        );

                $('div.progressBar')
                    .html('')
                    .width(0);
               $('#percents').html('0%');
               $('#progress_info').html('(initializing)');
                var container = $('div.results_errors');
                container.html('');
                var id = $('#progress_id').val();
                $.post(
                site_url+'db.php',
                {'action':'process',
                 'id':id},
                function (resp) {
                     if(resp.error){
                        alert(resp.msg);
                    }else{
                       // alert(resp.errors);
                        if (resp.errors.length > 0){
                            var container = $('div.results_errors');                
                            for(i=0;i<resp.errors.length;i++){
                                container.append(resp.errors[i]);
                                container.append('<br/>');
                            }
                            container.append('<br/>');
                            container.slideDown(200);
                        }
                    }
                    if (resp.error || (resp.errors.length > 0)){
                         clearTimeout(timeout_id);
                         $('div.progressBar').width('100%');
                        $('div.progressBar').html('Download is completed with errors!');
                        $('#ftp_update_data').show();
                    }
                    //window.location.href=window.location.href;
                },
                'json'
	        );

	        $('div.progress').slideDown(200);
                $('#ftp_update_data').hide();
	        setTimeout("show_ftp_download_status('', '"+id+"', 'get_ftp_download_status')",500);
	        return false;
	    })
	}     

         if($('#update_data').get(0)){
	    $('#update_data').click(function(){
               $.post(
                site_url+'item.php',
                {'action':'generate_id'},
                function (resp) {
                    $('#progress_id').val(resp);
                }
	        );

                $('div.progressBar')
                    .html('')
                    .width(0);
               $('#percents').html('0%');
               $('#progress_info').html('(initializing)');
                var container = $('div.results_errors');
                container.html('');
                var id = $('#progress_id').val();
                $.post(
                site_url+'item.php',
                {'action':'process',
                 'id':id},
                function (resp) {
                     if(resp.error){
                        alert(resp.msg);
                    }else{
                       // alert(resp.errors);
                        if (resp.errors && resp.errors.length > 0){
                            var container = $('#results_errors');
                            container.html('')
                            for(i=0;i<resp.errors.length;i++){
                                container.append(resp.errors[i]);
                                container.append('<br/>');
                            }
                            container.append('<br/>');
                            container.slideDown(200);

                            clearTimeout(timeout_id);
                            $('div.progress').hide();
	                    $('div.progressBar').html('');
                            $('#update_data').show();
                        }
                        if (resp.data){
                            var uploaded_files_container = $('#uploaded_files_container');
                            uploaded_files_container.html(resp.data);

                            $('.check_all').click(function(){
                                if($(this).hasClass('checked')){
                                    $('input[type=checkbox]').removeAttr('checked');
                                    $(this).removeClass('checked');
                                } else {
                                    $('input[type=checkbox]').attr('checked',true);
                                    $(this).addClass('checked');
                                }
                            });

                            $(".delete_profile").click(delete_profile);
                        }

                    }
                    //window.location.href=window.location.href;
                },
                'json'
	        );

	        $('div.progress').slideDown(200);
                $('#update_data').hide();
	        setTimeout("show_update_status('', '"+id+"', 'show_update_status')",500);
	        return false;
	    })
	}

        jQuery("#display_sn").click(function(){       
        
            if (jQuery("#display_sn").is(":checked"))
            {
                jQuery("#append_sn_to_first_row_control_holder").fadeIn(300);
            }
            else
            {
                jQuery("#append_sn_to_first_row_control_holder").fadeOut(300);
            }
          });
        jQuery("#combine_quantities").click(function(){
           if (jQuery("#combine_quantities").is(":checked"))
            {
                jQuery(".combineQuantities").fadeIn(300);
            }
            else
            {
                jQuery(".combineQuantities").fadeOut(300);
            }
        });

        jQuery("#submit").click(function(){
            if (jQuery("#combine_quantities").is(":checked"))
                {                 
                    var scan_column_number = jQuery("#scan_column_number").val();
                    if (!isInteger(scan_column_number) || !isPositiveInteger(scan_column_number)){
                       alert("Please enter a valid scan column index!");
                       jQuery("#scan_column_number").focus();
                       return false;
                    }

                    var quantity_column_number = jQuery("#quantity_column_number").val();
                    if (!isInteger(quantity_column_number) || !isPositiveInteger(quantity_column_number)){
                       alert("Please enter a valid quantity column index!");
                       jQuery("#quantity_column_number").focus();
                       return false;
                    }
                    
                    if (quantity_column_number == scan_column_number){
                        alert("Quantity column index and scan column index must be different!");
                       return false;
                    }
                }
                return true;
        });
       
        $('.profiles_check_all').click(function(){
            if($(this).hasClass('checked')){
                $('input.profile_check[type=checkbox]').removeAttr('checked');
                $(this).removeClass('checked');
            }else {
                $('input.profile_check[type=checkbox]').attr('checked',true);
                $(this).addClass('checked');
            }
        });

        jQuery("#profile_selection").change(update_profile_list);
        jQuery("#profile_platform_selection").change(update_profile_list);

        $(".assign_profile").click(assign_profile);
        $(".remove_profile").click(remove_assigned_profile);

        $('.check_all').click(function(){
            if($(this).hasClass('checked')){
                $('input[type=checkbox]').removeAttr('checked');
                $(this).removeClass('checked');
            } else {
                $('input[type=checkbox]').attr('checked',true);
                $(this).addClass('checked');
            }
        });
        $('#priceuploadform').submit(function() {           
                $('div.progressBar')
                    .html('')
                    .width(0);
               $('#percents').html('0%');
               $('#progress_info').html('(initializing)');
                var container = $('#results_errors');
                container.empty();

                var options = {
                    beforeSubmit:  priceSubmitRequest,
                    error:      priceSubmitResponse,
                    success:    priceSubmitResponse,
                    url:       'price_upload.php',
                    dataType:  'json'
                };

                $('div.progress').slideDown(200);
                $('#submit_file').hide();                

		$(this).ajaxSubmit(options);

                var progress_id = $('#progress_id').val();
	        setTimeout("show_progress_status('get_status.php', '"+progress_id+"', 'get_price_upload_status')",500);             
               
		return false;
	});

       bindDeleteProfileLinkClickHandler();
       $(".delete_profile").click(delete_profile);

        $('#uploadoihtemplateform').submit(function() {
            $('#fileloading').show();
            $('#error_message').empty();

            var options = {
                beforeSubmit:  uploadFileSubmitRequest,
                error:      oihTemplateSubmitResponse,
                success:    oihTemplateSubmitResponse,
                url:       'oih_template_upload.php',
                dataType:  'json'
            };

            $(this).ajaxSubmit(options);
            return false;
	});

      bindDeleteOIHTemplateLinkClickHandler();
      $(".delete_template").click(deleteSelectedOIHTemplates);

      bindProfileActionLinksClickHandler();

      bindAddProfileActions();
      bindSendProfileCopy();

       if($('#add_action_form').get(0)){
        $('#add_action_form').submit(function(){
            var profile_action = $('#profile_action');
            var selectedValue = profile_action.val();
            if (selectedValue == '-'){
                alert('Please select action!');
                profile_action.focus();
                return false;
            }else{
                var platform = $('#platform').val();
                
                // Validate
                switch(selectedValue){
                    case 'CLIP DATA':
                        var clip_data_start = $('#clip_data_start');
                        var clip_data_start_value = clip_data_start.val();
                        if(clip_data_start_value == ''){
                            alert('Please specify start!');
                            clip_data_start.focus();
                            return false;
                        }

                        if(!/^[0-9]+$/.test($('#clip_data_start').val())){
                            alert('Please specify valid number!');
                            $('#clip_data_start').focus();
                            return false;
                        }

                        if ($('#useLength').is(':checked')){
                            var clip_data_length = $('#clip_data_length');
                            var clip_data_length_value = clip_data_length.val();
                            if(clip_data_length_value == ''){
                                alert('Please specify length!');
                                clip_data_length.focus();
                                return false;
                            }
                            if(!/^[0-9]+$/.test($('#clip_data_length').val())){
                                alert('Please specify valid number!');
                                $('#clip_data_length').focus();
                                return false;
                            }
                        }else{
                            var clip_data_end = $('#clip_data_end');
                            var clip_data_end_value = clip_data_end.val();
                            if(clip_data_end_value == ''){
                                alert('Please specify end!');
                                clip_data_end.focus();
                                return false;
                            }
                            if(!/^[0-9]+$/.test($('#clip_data_end').val())){
                                alert('Please specify valid number!');
                                $('#clip_data_end').focus();
                                return false;
                            }
                        }
                        break;
                    case 'POST TEXT':
                    case 'TEXT':
                        if($('#text').val() == ''){
                            alert('Please specify text!');
                            $('#text').focus();
                            return false;
                        }
                        break;
                    case 'GOTO CELL':
                         var goto_cell_type = $('#goto_cell_type');
                         var goto_cell_type_value = goto_cell_type.val();
                         if (goto_cell_type_value == 'Specified location'){                            
                            if($('#goto_cell_column').val() == ''){
                                alert('Please specify column!');
                                $('#goto_cell_column').focus();
                                return false;
                            }
                            if(!/^[0-9]+$/.test($('#goto_cell_column').val())){
                                alert('Please specify valid number!');
                                $('#goto_cell_column').focus();
                                return false;
                            }
                            if($('#goto_cell_row').val() == ''){
                                alert('Please specify row!');
                                $('#goto_cell_row').focus();
                                return false;
                            }
                            if(!/^[0-9]+$/.test($('#goto_cell_row').val())){
                                alert('Please specify valid number!');
                                $('#goto_cell_row').focus();
                                return false;
                            }
                        }
                        break;
                    case 'SET COLUMN NAMES':
//                        if($('#set_columns_name1').val() == ''){
//                            alert('Please specify column 1!');
//                            $('#set_columns_name1').focus();
//                            return false;
//                        }
                        break;
                    case 'SHOW PROMPT':
                         if($('#prompt_text').get(0)){
                            if($('#prompt_text').val() == ''){
                                alert('Please specify message!');
                                $('#prompt_text').focus();
                                return false;
                            } 
                         }
                         if($('#prompt_min').get(0)){
                             if($('#prompt_min').val() != ''){
                                  if(!/^[0-9]+$/.test($('#prompt_min').val())){
                                    alert('Please specify valid number!');
                                    $('#prompt_min').focus();
                                    return false;
                                  }
                            }
                         }
                         if($('#prompt_max').get(0)){
                             if($('#prompt_max').val() != ''){
                                 if(!/^[0-9]+$/.test($('#prompt_max').val())){
                                    alert('Please specify valid number!');
                                    $('#prompt_max').focus();
                                    return false;
                                }
                             }
                         }
                        break;
                    case 'SHOW MESSAGE':
                        if($('#show_message_value').val() == ''){
                            alert('Please specify message!');
                            $('#show_message_value').focus();
                            return false;
                        }
                        break;
                    case 'GET VARIABLE':
                    case 'SET VARIABLE':
                        if($('#variable_name').val() == ''){
                            alert('Please specify variable name!');
                            $('#variable_name').focus();
                            return false;
                        }
                        if (selectedValue == 'SET VARIABLE'){
                             if($('#variable_value').val() == ''){
                                alert('Please specify variable value!');
                                $('#variable_value').focus();
                                return false;
                            }
                        }
                        break;
                    case 'DATE-TIME':
                        if($('#format').val() == ''){
                            alert('Please specify format!');
                            $('#format').focus();
                            return false;
                        }
                        break;
                    case 'IMAGE-TAKE':
                        if ($('#image_take_size2').is(':checked')){
                            var custom_image_size =$('#custom_image_size');
                            var custom_image_size_value = custom_image_size.val();
                            if(custom_image_size_value == ''){
                                alert('Please specify size!');
                                custom_image_size.focus();
                                return false;
                            }else{
                                var show_error = false;
                                if (custom_image_size_value.indexOf("x") == -1){
                                   show_error = true;
                                }else{
                                    var partsArray = custom_image_size_value.split('x');
                                    if (partsArray.length != 2){
                                        show_error = true;
                                    }else{
                                       if(!/^[0-9]+$/.test(partsArray[0]) || !/^[0-9]+$/.test(partsArray[1])){
                                        show_error = true;
                                       }
                                    }
                                }

                                if (show_error){
                                    alert('Please specify valid format size!');
                                    custom_image_size.focus();
                                    return false;
                                }
                            }
                        }
                        break;
                    case 'PROMPT-TEXT':
                    case 'PROMPT-MESSAGE':
                        if($('#promt_text_value').val() == ''){
                            alert('Please specify message!');
                            $('#promt_text_value').focus();
                            return false;
                        }
                        break;
                    case 'IF':
                        if (platform == 'iOS'){
                            var if_variable = $('#if_variable');
                            var if_variable_value = if_variable.val();
                            if(if_variable_value != 'GRID EMPTY'){
                                 if($('#if_value').val() == ''){
                                    alert('Please specify value!');
                                    $('#if_value').focus();
                                    return false;
                                }
                            }
                        }else{
                          var if_condition = $('#if_condition');
                            var if_condition_value = if_condition.val();
                            switch(if_condition_value){
                                case 'LENGTH':
                                     if($('#length_value').val() == ''){
                                        alert('Please specify length value!');
                                        $('#length_value').focus();
                                        return false;
                                    }
                                    break;
                                case 'MATCH':
                                    if($('#match_substring').val() == ''){
                                        alert('Please specify substring!');
                                        $('#match_substring').focus();
                                        return false;
                                    }
                                    if($('#match_substring_position').val() == ''){
                                        alert('Please specify substring position!');
                                        $('#match_substring_position').focus();
                                        return false;
                                    }
                                    if(!/^[0-9]+$/.test($('#match_substring_position').val())){
                                        alert('Please specify valid substring position!');
                                        $('#match_substring_position').focus();
                                        return false;
                                    }
                                    break;
                                case 'EACH_N_SCAN':
                                     if($('#n_value').val() == ''){
                                        alert('Please specify modulus of scans number!');
                                        $('#n_value').focus();
                                        return false;
                                    }
                                    if(!/^[0-9]+$/.test($('#n_value').val())){
                                        alert('Please specify valid modulus of scans number!');
                                        $('#n_value').focus();
                                        return false;
                                    }
                                    break;
                                case 'COLUMN_POS_N':
                                     if($('#n_value').val() == ''){
                                        alert('Please specify column number!');
                                        $('#n_value').focus();
                                        return false;
                                    }
                                    if(!/^[0-9]+$/.test($('#n_value').val())){
                                        alert('Please specify valid column number!');
                                        $('#n_value').focus();
                                        return false;
                                    }
                                    break;
                            };
                        }

                        break;
                    case 'SET-DATA':
                    case 'GET-DATA':
                        if($('#marker_value').val() == ''){
                            alert('Please specify marker value!');
                            $('#marker_value').focus();
                            return false;
                        }
                        break;
                    case 'LABEL':
                    case 'JUMP':
                    case 'JUMP LABEL':
                        if($('#name_value').val() == ''){
                            alert('Please specify name!');
                            $('#name_value').focus();
                            return false;
                        }
                        break;
                    case 'GET-PREF':
                    case 'SET-PREF':
                        if($('#preference_name').val() == ''){
                            alert('Please specify preferense name!');
                            $('#preference_name').focus();
                            return false;
                        }
                        if (selectedValue == 'SET-PREF'){
                             if($('#preference_value').val() == ''){
                                alert('Please specify preferense value!');
                                $('#preference_value').focus();
                                return false;
                            }
                        }
                        break;
                    case 'PLAY-AUDIO':
                        if ($('#play_audio_type').val() == 'filename'){
                            var play_audio_filename = $('#play_audio_filename_value');
                            var play_audio_filename_value = play_audio_filename.val();
                            if(play_audio_filename_value == ''){
                                alert('Please specify filename value!');
                                play_audio_filename.focus();
                                return false;
                            }
                        }
                        break;
                   case 'GIH-GOTO-CELL':
                        if (!$('#gih_goto_cell_control').is(':checked') && !$('#gih_goto_cell_control2').is(':checked')){
                            alert('Please set action parameterss!');
                            return false;
                        }
                       if ($('#gih_goto_cell_control').is(':checked')){
                             if($('#gih_goto_cell_column').val() == ''){
                                alert('Please specify column!');
                                $('#gih_goto_cell_column').focus();
                                return false;
                            }
                            if(!/^[0-9]+$/.test($('#gih_goto_cell_column').val())){
                                alert('Please specify valid column number!');
                                $('#gih_goto_cell_column').focus();
                                return false;
                            }

                             if($('#gih_goto_cell_row').val() == ''){
                                alert('Please specify column!');
                                $('#gih_goto_cell_row').focus();
                                return false;
                            }
                            if(!/^[0-9]+$/.test($('#gih_goto_cell_row').val())){
                                alert('Please specify valid column number!');
                                $('#gih_goto_cell_row').focus();
                                return false;
                            }
                       }
                       break;
                }
            }

            return true;
        })
    }

     if($('#profile_action').get(0)){
        $('#profile_action').change(function(){
            var profile_action = $('#profile_action');
            var selectedValue = profile_action.val();
            
            $('.action_param').hide();

            $('#marker_value').val('');
            $('#name_value').val('');
            $('#promt_text_value').val('');
            $('#preference_name').val('');

            clearProfileActionIfCondition();

            if (selectedValue != '-'){
                switch(selectedValue){
                    case 'CLIP DATA':
                        $('#clip_data_help_block').show();
                        $('#clip_data_start_block').show();
                        $('#clip_data_end_block').show();
                        $('#clip_data_length_block').show();
                        $('#clip_data_use_length_block').show();
                        $('#clip_data_scan_block').show();
                        break;
                    case 'POST DATE TIME':
                        $('#date_time_help_block').show();
                        $('#post_date_time_format_block').show();
                        break;
                    case 'POST DECODE JDATE':
                        $('#post_decode_jdate_help_block').show();
                        $('#post_decode_jdate_format_block').show();
                        break;
                    case 'GOTO CELL':
                        $('#goto_cell_help_block').show();
                        $('#goto_cell_block').show();
                        $('#goto_cell_direction_block').show();
                        break;
                    case 'SET COLUMN NAMES':
                        $('#set_column_names_help_block').show();
                        $('#set_columns_names1_block').show();
                        $('#set_columns_names2_block').show();
                        $('#set_columns_names3_block').show();
                        break;
                    case 'SHOW PROMPT':
                        $('#show_prompt_help_block').show();
                        $('#show_prompt_block').show();
                        $('#fullOskb_block').show();
                        $('#prompt_min_block').show();
                        $('#prompt_max_block').show();
                        $('#prompt_default_value_block').show();
                        break;
                    case 'SHOW MESSAGE':
                        $('#show_message_help_block').show();
                        $('#show_message_block').show();
                        break;
                    case 'JUMP LABEL':
                        $('#jump_label_help_block').show();
                        $('#name_block').show();
                        break;
                    case 'EXIT':
                        $('#exit_help_block').show();
                        break;
                    case 'NEW GRID':
                        $('#new_grid_help_block').show();
                        break;
                    case 'CLEAR VARIABLES':
                        $('#clear_variable_help_block').show();
                        break;
                    case 'SET VARIABLE':
                        $('#set_variable_help_block').show();
                        $('#variable_name_block').show();
                        $('#variable_value_block').show();
                        break;
                    case 'GET VARIABLE':
                        $('#get_variable_help_block').show();
                        $('#variable_name_block').show();
                        break;
                    case 'PARSE HIBC CODE':
                        $('#parse_hibc_help_block').show();
                        break;

                    case 'POST SCAN DATA':
                        $('#post_scan_data_help_block').show();
                        break;
                    case 'POST DATA':
                        $('#post_data_help_block').show();
                        break;
                    case 'TEXT':
                    case 'POST TEXT':
                        $('#text_help_block').show();
                        $('#text_param_block').show();
                        break;
                    case 'DATE-TIME':
                        $('#date_time_help_block').show();
                        $('#date_time_format_block').show();
                    break;
                    case 'POST-SCANNER-SN':
                        $('#post_scanner_sn_help_block').show();
                    break;
                    case 'SIGNATURE-CAPTURE':
                        $('#signature_capture_help_block').show();
                    break;
                    case 'IMAGE-TAKE':
                        $('#image_take_format_block').show();
                        $('#image_take_help_block').show();
                    break;
                    case 'GIH-SHOW':
                        $('#gih_show_help_block').show();
                    break;
                    case 'KEY':
                        $('#key_format_block').show();
                        $('#key_help_block').show();
                    break;
                    case 'GIH-SET-COLUMNS':
                        $('#gih_set_columns_names_block').show();
                        $('#gih_set_columns_hidden_columns_block').show();
                        $('#gih_set_columns_help_block').show();
                    break;
                    case 'PROMPT-TEXT':
                    case 'PROMPT-MESSAGE':
                        $('#prompt_text_block').show();
                        if (selectedValue == 'PROMPT-MESSAGE'){
                            $('#prompt_message_help_block').show();
                            $('#prompt_btn1_block').show();
                            $('#prompt_btn2_block').show();
                            $('#prompt_btn3_block').show();
                        }else{
                            $('#prompt_text_help_block').show();
                        }
                    break;
                    case 'PROMPT NUM':
                        $('#prompt_num_help_block').show();
                    break;
                    case 'POST NUM':
                        $('#post_num_help_block').show();
                    break;
                    case 'POST-TEXT':
                        $('#post_text_help_block').show();
                    break;
                    case 'POST-LOCATION':
                        $('#post_location_help_block').show();
                        $('#post_location_block').show();
                    break;
                    case 'IF':
                        $('#if_help_block').show();
                        $('#if_condition_block').show();
                        $('#if_condition').val('LENGTH');
                        $('#length_condition_help_block').show();
                        $('#length_block').show();
                        $('#length_block2').show();
                        $('#inverse_block').show();

                        $('#if_variable_block').show();
                        $('#length_help_block').show();
                        $('#iphone_if_condition').show();
                        $('#if_value_block').show();
                    break;
                    case 'ELSE':
                        $('#else_help_block').show();
                    break;
                    case 'ENDIF':
                        $('#endif_help_block').show();
                    break;
                    case 'DONE':
                        $('#done_help_block').show();
                    break;
                    case 'SET-DATA':
                    case 'GET-DATA':
                        $('#marker_block').show();
                        if (selectedValue ==  'SET-DATA'){
                            $('#set_data_help_block').show();
                        }else{
                            $('#get_data_help_block').show();
                        }
                    break;
                    case 'LABEL':
                    case 'JUMP':
                        $('#name_block').show();
                        if (selectedValue == 'LABEL'){
                            $('#label_help_block').show();
                        }else if (selectedValue == 'JUMP'){
                            $('#jump_help_block').show();
                        }            
                    break;
                    case 'GET-PREF':
                        $('#get_pref_help_block').show();
                        $('#preference_name_block').show();
                    break;
                    case 'SET-PREF':
                        $('#set_pref_help_block').show();
                        $('#preference_name_block').show();
                        $('#preference_value_block').show();
                    break;
                    case 'GET-TIME':
                        $('#get_time_help_block').show();
                    break;
                    case 'PLAY-AUDIO':
                        $('#play_audio_help_block').show();
                        $('#play_audio_block').show();
                    break;
                    case 'GIH-GOTO-CELL':
                        $('#gih_goto_cell_help_block').show();
                        $('#gih_goto_cell_block').show();
                        break;
                    case 'DB-GET-VALUE':
                        $('#db_get_value_help_block').show();
                        $('#db_get_value_block').show();
                        if ($('#items_databases').length == 1){
                            // display tables if database is only one
                            $('#db_get_value_block_tables').show();
                            $('#db_get_value_block_lookup_fields').show();
                            $('#db_get_value_block_get_fields').show();
                        }
                        break;
                    case 'DB-GET-ROW':
                    case 'DB-SHOW-INFO':
                        if (selectedValue == 'DB-GET-ROW'){
                        $('#db_get_row_help_block').show();
                             $(".item_database_tables").removeAttr('noaction');
                        }else{
                            $(".item_database_tables").attr('noaction', 1);
                        }
                        $('#db_get_row_block').show();
                        if ($('#items_databases').length == 1){
                            // display tables if database is only one
                            $('#db_get_row_block_tables').show();
                            if (selectedValue == 'DB-GET-ROW'){
                            $('#db_get_row_block_lookup_fields').show();
                        }
                        }
                        break;
                    case 'DB-POST-FROM-ROW':
                        $('#db_post_from_help_block').show();
                        $('#db_post_from_row_block').show();
                        break;
                }
            }

            return true;
        })
                }

    bindItemsDatabaseTables();
 
    if($('.item_databases').get(0)){
        $('.item_databases').change(function(){

            var onlylookupfield = $(this).attr('onlylookupfield');
            if (onlylookupfield  == '1'){
                 var databases = $('#items_databases_for_row');
            }else{
                var databases = $('#items_databases');
            }

            var database = databases.val();
            jQuery('#div-loader').show();

            jQuery.post(
                site_url+'profile_action.php',
                {
                    'action':'get_tables_and_fields',
                    'database':database,
                    'onlylookupfield':onlylookupfield
                },
                function (resp) {
                    $('#div-loader').hide();
                    if(resp.errors){
                            var error = '';
                            $(resp.errors).each(function(k,v){
                                    error += v+'\n';
                            })
                            alert(error);
                    }

                    if (resp.onlylookupfield == '1'){
                        var tables_block = $("#db_get_row_block_tables");
                        var lookup_fields = $("#db_get_row_block_lookup_fields");                       
                    }else{
                        var tables_block = $("#db_get_value_block_tables");
                        var lookup_fields = $("#db_get_value_block_lookup_fields");

                        var get_fields = $("#db_get_value_block_get_fields");
                        get_fields.replaceWith(resp.get_fields_html);
                        get_fields.show();
                    }

                    bindItemsDatabaseTables();

                    tables_block.replaceWith(resp.tables_block_html);
                    tables_block.show();

                    lookup_fields.replaceWith(resp.lookup_fields_html);
                    lookup_fields.show();
                },
                "json"
                );

            return true;
        })
    }

    if($('#play_audio_type').get(0)){
        $('#play_audio_type').change(function(){
            var type = $('#play_audio_type');
            var selectedValue = type.val();

            $('#play_audio_predefined_value').hide();
            $('#play_audio_filename_value').hide();

            switch(selectedValue){
                case 'predefined':
                    $('#play_audio_predefined_value').show();
                    break;
                case 'filename':
                    $('#play_audio_filename_value').show();
                break;
            }

            return true;
        })
    }

    if($('#goto_cell_type').get(0)){
        $('#goto_cell_type').change(function(){
            var type = $('#goto_cell_type');
            var selectedValue = type.val();

            $('#goto_cell_direction_block').hide();
            $('#goto_cell_column_block').hide();
            $('#goto_cell_row_block').hide();

            switch(selectedValue){
                case 'Direction':
                    $('#goto_cell_direction_block').show();
                    break;
                case 'Specified location':
                    $('#goto_cell_column_block').show();
                    $('#goto_cell_row_block').show();
                break;
            }

            return true;
        })
    }

    $("#gih_goto_cell_control").change(function(){
         if ($(":radio[name=gih_goto_cell_control]:checked").val() == "true") {
            $('#gih_goto_cell_column_block').show();
            $('#gih_goto_cell_row_block').show();
            $('#gih_goto_cell_find_empty_row_block').hide();
        }else{
            $('#gih_goto_cell_find_empty_row_block').show();
            $('#gih_goto_cell_row_block').hide();
            $('#gih_goto_cell_column_block').hide();
        }
    });
    
    $("#gih_goto_cell_control2").change(function(){
         if ($(":radio[name=gih_goto_cell_control]:checked").val() == "true") {
            $('#gih_goto_cell_column_block').show();
            $('#gih_goto_cell_row_block').show();
            $('#gih_goto_cell_find_empty_row_block').hide();
        }else{
            $('#gih_goto_cell_find_empty_row_block').show();
            $('#gih_goto_cell_row_block').hide();
            $('#gih_goto_cell_column_block').hide();
        }
    });

    $("#image_take_size").change(function(){
        if ($("input[@name='image_take_size']:checked").val() == 'standard') {
            $('#image_size').show();
            $('#custom_image_size_block').hide();
        }else{
            $('#custom_image_size_block').show();
            $('#image_size').hide();
        }
    });
    
    $("#image_take_size2").change(function(){
        if ($("input[@name='image_take_size']:checked").val() == 'standard') {
            $('#image_size').show();
            $('#custom_image_size_block').hide();
        }else{
            $('#custom_image_size_block').show();
            $('#image_size').hide();
        }
    });

     if($('#if_condition').get(0)){
        $('#if_condition').change(function(){
            var if_condition = $('#if_condition');
            var selectedValue = if_condition.val();

            clearProfileActionIfCondition();
            
            if (selectedValue != '-'){
                switch(selectedValue){
                    case 'LENGTH':
                        $('#length_condition_help_block').show();
                        $('#length_block').show();
                        $('#length_block2').show();
                        break;
                    case 'MATCH':
                        $('#match_condition_help_block').show();
                        $('#match_substring_block').show();
                        $('#match_substring_position_block').show();
                    break;
                    case 'EACH_N_SCAN':
                    case 'COLUMN_POS_N':
                        if (selectedValue == 'EACH_N_SCAN'){
                            $('#each_n_scan_condition_help_block').show();
                        }else{
                            $('#column_pos_n_help_block').show();
                        }
                        $('#n_value_block').show();
                    break;
                    case 'LOGIN-TODAY':
                         $('#login_today_help_block').show();
                        break;
                }
            }

            return true;
        })
    }

    if($('#if_variable').get(0)){
        $('#if_variable').change(function(){
            var if_variable = $('#if_variable');
            var selectedValue = if_variable.val();

             $('#length_help_block').hide();
             $('#scan_data_help_block').hide();
             $('#data_help_block').hide();
             $('#column_help_block').hide();
             $('#grid_empty_help_block').hide();

             $('#if_condition_block').show();
             $('#if_value_block').show();

            switch(selectedValue){
                case 'LENGTH':
                    $('#length_help_block').show();
                    break;
                case 'SCAN DATA':
                    $('#scan_data_help_block').show();
                    break;
                case 'DATA':
                    $('#data_help_block').show();
                    break;
                case 'COLUMN':
                    $('#column_help_block').show();
                    break;
                case 'GRID EMPTY':
                    $('#grid_empty_help_block').show();
                    $('#if_condition_block').hide();
                    $('#if_value_block').hide();
                    break;

                    return true;
            }
        })
    }

    bindDeleteDMPLinksClickHandler();

});

function clearProfileActionIfCondition(){
    $('#length_block').hide();
    $('#length_block2').hide();
    $('#match_substring_block').hide();
    $('#match_substring_position_block').hide();
    $('#n_value_block').hide();

    $('#length_condition_help_block').hide();
    $('#match_condition_help_block').hide();
    $('#each_n_scan_condition_help_block').hide();
    $('#column_pos_n_help_block').hide();
    $('#login_today_help_block').hide();

    $('#n_value').val('');
}

function delete_profile(event){
    var name = $(this).attr('name');

    var action;
    if (name == 'submit'){
        action = $('#delete_profile').val();
    }else{
        action = $('#delete_profile2').val();
    }
    if (action == 0){
        alert('Please select action!');
        return false;
    }

    var selectedProfiles = new Array();
    $(".item_check").each(function() {
            if ($(this).is(':checked')){
        selectedProfiles.push($(this).val());
            }
    });

    if (selectedProfiles.length == 0){
        alert('Please select files to remove!');
        return false;
    }
}

function uploadFileSubmitRequest(formData, jqForm, options) {
    var fileToUploadValue = jQuery('#uploadfile').fieldValue();
    if (!fileToUploadValue[0]) {
        jQuery('#fileloading').hide();
        jQuery(' #error_message').html('Please select a file.');
        return false;
    }
    return true;
}
function bindDeleteProfileLinkClickHandler(){
        // First unbind handler
         jQuery(".deleteprofilelink").unbind('click');         

         jQuery(".deleteprofilelink").click(function(){
             var link = jQuery(this);           
             var profile_id = link.attr('profile_id');
             
             var result = confirm('Are you sure you want to delete profile?');
             if(result == false){
                 return;
             }

         jQuery('#div-loader').show();

             jQuery.post(
                site_url+'profiles.php',
                {'action':'delete',                
                 'profile_id':profile_id
                },
                 function (resp) {
                        if (resp.error){
                            alert(resp.error);
                        }else{ 
                        buildProfileList(resp.data);
                        }
                    },
                    "json"
	        );
         });
    }
function buildProfileList(data){     
    jQuery('#profiles_container').html(data);
    jQuery('#div-loader').hide();

    bindDeleteProfileLinkClickHandler();

    $('.profiles_check_all').click(function(){
        if($(this).hasClass('checked')){
            $('input.profile_check[type=checkbox]').removeAttr('checked');
            $(this).removeClass('checked');
        } else {
            $('input.profile_check[type=checkbox]').attr('checked',true);
            $(this).addClass('checked');
        }
    });

    $(".assign_profile").click(assign_profile);
    $(".remove_profile").click(remove_assigned_profile);

    $.collapsible(".module .header");

    if($('form.ajax_data').get(0)) {
        $('form.ajax_data').each(function(){
            init_ajax_data_form(this);
        })
    }
    bindAssignProfilesTo();
}
function oihTemplateSubmitResponse(data, statusText)  {
    $('#fileloading').hide();
    jQuery('#uploadfile').val('');
    if(data.error != undefined && data.error != ''){
        jQuery('#error_message').html(data.error);
    }
    if (statusText == 'success') {        
         buildOIHTemplateList(data.templates);
    }
}

function bindDeleteOIHTemplateLinkClickHandler(){

     jQuery(".deleteoihtemplatelink").unbind('click');

     jQuery(".deleteoihtemplatelink").click(function(){
         var link = jQuery(this);
         var id = link.attr('id');

         var result = confirm('Are you sure you want to delete template?');
         if(result == false){
             return;
         }

         jQuery('#loading').show();

         jQuery.post(
            site_url+'oih_templates.php',
            {'action':'delete',
             'id':id
            },
             function (resp) {
                    if (resp.error){
                        alert(resp.error);
                    }else{
                        buildOIHTemplateList(resp.templates);
                    }
                },
                "json"
            );
     });
}

function buildOIHTemplateList(templates){
     var template_data;
     if (templates != undefined && templates.length != 0){
        template_data = '<table class="lists"><tr><th align="center" width="15px"><a title="check/uncheck all" class="check_all" href="javascript:void(0)"></a></th><th>Name</th><th>Date created</th><th></th></tr>';
        template_data += '<tr><td colspan="4" align="left">With selected:&nbsp;<input type="button" value="Delete" class="delete_template"/></td></tr><tr>';
        for(i=0;i<templates.length;i++){
            template_data += '<tr><td align="center"><input class="item_check" type="checkbox" value="'+templates[i]['id']+'" name="lists[]" /></td>';
            template_data += '<td align="center">'+templates[i]['name']+'</td>';
            template_data += '<td>'+templates[i]['created']+'</td>';
            template_data += '<td><div class="deleteoihtemplatelink" id="'+templates[i]['id']+'">Delete</div></td></tr>';
        }
        template_data += '<tr><td colspan="4" align="left">With selected:&nbsp;<input type="button" value="Delete" class="delete_template"/></td></tr><tr>';
        template_data += '</tr></table>';
     }else{
        template_data = ' <br><b>You have no OIH templates available to view.</b><br>';
     }

     //var container = $('#templates_container');
     //container.html(template_data);
     //var tmp = container.html();
     $('#templates_container').html(template_data);
     $('#loading').hide();

    bindDeleteOIHTemplateLinkClickHandler();

     $('.check_all').click(function(){
        if($(this).hasClass('checked')){
            $('input[type=checkbox]').removeAttr('checked');
            $(this).removeClass('checked');
        } else {
            $('input[type=checkbox]').attr('checked',true);
            $(this).addClass('checked');
        }
    });
    $(".delete_template").click(deleteSelectedOIHTemplates);
}

function deleteSelectedOIHTemplates(event){
    var selectedProfiles = new Array();
    $("input[@name='lists[]']:checked").each(function() {
        selectedProfiles.push($(this).val());
    });

    if (selectedProfiles.length == 0){
        alert('Please select template to delete!');
        return;
    }

    $('#loading').show();
    $.post(
        site_url+'oih_templates.php',
        {'action':'delete_templates',
         'template_ids':selectedProfiles.join(',')},
             function (resp) {
                $('#loading').hide();
                 if (resp.error){
                    alert(resp.error);
                }else{
                    buildOIHTemplateList(resp.templates);
                }
            },
            "json"
        );
}

function assign_profile(event){
    var name = $(this).attr('name');

    var group_id;
    if (name == 'assign'){
        group_id = $('#assign_profile').val();
    }else{
        group_id = $('#assign_profile2').val();
    }
    if (group_id == 0){
        alert('Please select group!');
        return;
    }

    var selectedProfiles = new Array();
    $("input[@name='lists[]']:checked").each(function() {
        selectedProfiles.push($(this).val());
    });

    if (selectedProfiles.length == 0){
        alert('Please select profiles to assign!');
        return;
    }

    $('#div-loader').show();
    $.post(
        site_url+'profiles.php',
        {'action':'assign_profile',
         'group_id':group_id,
         'profile_ids':selectedProfiles.join(',')},
             function (resp) {
                $('#div-loader').hide();
                var msg;
                if (resp != null && resp.error){
                   msg = resp.error;
                }else{                   
                    $("input[@name='lists[]']:checked").each(function() {
                        $(this).removeAttr('checked');
                    });
                    $('#assign_profile').val('0');
                    $('#assign_profile2').val('0');
                    msg = "Profile was assigned.";
                }
                alert(msg);
            },
            "json"
        );
}

function remove_assigned_profile(event){
    var name = $(this).attr('name');

    var action;
    if (name == 'submit'){
        action = $('#remove_profile').val();
    }else{
        action = $('#remove_profile2').val();
    }
    if (action == 0){
        alert('Please select action!');
        return;
    }

    var selectedProfiles = new Array();
    $("input[@name='lists[]']:checked").each(function() {
        selectedProfiles.push($(this).val());
});

    if (selectedProfiles.length == 0){
        alert('Please select profiles to remove!');
        return;
    }

    var group_id = $('#profile_selection').val();
    var platform = $('#profile_platform_selection').val();

    $('#div-loader').show();
    $.post(
        site_url+'profiles.php',
        {'action':'remove_profile',
         'group_id':group_id,
         'platform':platform,
         'profile_ids':selectedProfiles.join(',')},
             function (resp) {
                $('#div-loader').hide();
                var msg;
                if (resp != null && resp.error){
                   msg = resp.error;
                }else{
                    var profiles_container = $('#profiles_container');
                    profiles_container.html(resp.data);

                    $("input[@name='lists[]']:checked").each(function() {
                        $(this).removeAttr('checked');
                    });
                    $('#remove_profile').val('0');
                    $('#remove_profile2').val('0');
                    msg = "Profile was removed.";

                    $(".remove_profile").click(remove_assigned_profile);
                }
                alert(msg);
            },
            "json"
        );        
}

function show_geo_status(url,file_id){
    $.post(
        site_url+"get_status.php",
        {'action':'get_status',
         'file_id':file_id},
        function (resp) {
            if(resp!='error'){
                if(resp.processed>0){
	                var processed = resp.processed;
	                var total_rows = resp.num_rows;
	                var percent_complete = Math.ceil((resp.processed/resp.num_rows)*100);
	                var progress_length = percent_complete*3;
	                $('div.progressBar').width(progress_length);
	                $('#percents').html(percent_complete+'%');
	                $('#progress_info').html(processed+' from '+total_rows);
	                if(total_rows == processed){
	                    clearTimeout(timeout_id);
	                    $('div.progressBar').html('Updating file...');
	                }
                }
            }
        },
        'json'
    )
    counter++;
    timeout_id = setTimeout("show_geo_status('"+url+"',"+file_id+")",2000);
}

function show_ftp_download_status(url, id, action){
   
    $.post(
        site_url+"get_status.php",
        {'action':action,
         'id':id},
        function (resp) {
            if(resp!='error'){
                if(resp.processed>=0){
	               var processed = resp.processed;
	                var total_rows = resp.num_rows;
                        if (resp.processed == 0 && resp.num_rows == 0){
                            var percent_complete = 100;
                        }else{
	                var percent_complete = Math.ceil((resp.processed/resp.num_rows)*100);
                        }
	                var progress_length = percent_complete*3;
	                $('div.progressBar').width(progress_length);
	                $('#percents').html(percent_complete+'%');
	                $('#progress_info').html(processed+' of '+total_rows);
	                if(total_rows == processed){
	                    clearTimeout(timeout_id);
	                    $('div.progressBar').html('Download is completed!');
                            $('#ftp_update_data').show();
	                }
                }
            }else{
                clearTimeout(timeout_id);
            }
        },
        'json'
    )
    timeout_id = setTimeout("show_ftp_download_status('"+url+"', '"+id+"', 'get_ftp_download_status')",500);
}

function show_update_status(url, id, action){

    $.post(
        site_url+"get_status.php",
        {'action':action,
         'id':id},
        function (resp) {
            if(resp!='error'){
                if(resp.processed>=0){
	               var processed = resp.processed;
	                var total_rows = resp.num_rows;
	                var percent_complete = Math.ceil((resp.processed/resp.num_rows)*100);
	                var progress_length = percent_complete*3;
	                $('div.progressBar').width(progress_length);
	                $('#percents').html(percent_complete+'%');
	                $('#progress_info').html(processed+' of '+total_rows);
	                if(total_rows == processed){
	                    clearTimeout(timeout_id);
	                    $('div.progressBar').html('Download is completed!');
                            $('#update_data').show();
	                }
                }
            }else{
                clearTimeout(timeout_id);
            }
        },
        'json'
    )
    timeout_id = setTimeout("show_update_status('"+url+"', '"+id+"', 'show_update_status')",500);
}

function priceSubmitRequest(formData, jqForm, options) {
    var file = $('#discountfile');
    var fileToUploadValue = file.fieldValue();
    if (!fileToUploadValue[0]) {
        if (progress_timeout_id != 'undefined'){
           clearTimeout(progress_timeout_id);
        }
        $('div.progress').hide();
        $('#submit_file').show();
        $('#results_errors').html('Please select a file.');
        return false;
    }
    return true;
}
function priceSubmitResponse(data, statusText)  {
   
    if(data.error != undefined && data.error != ''){
        jQuery('#results_errors').html(data.error);
    }
    if (statusText == 'success') {
        if (data.errors.length > 0){
             clearTimeout(progress_timeout_id);
             $('div.progress').hide();
             $('#submit_file').show();

            var container = $('div.results_errors');
            for(i=0;i<data.errors.length;i++){
                container.append(data.errors[i]);
                container.append('<br/>');
            }
            container.append('<br/>');
            container.show();
            $('div.progress').hide();
            $('#discountfile').val('');
        }
    }
}
function show_progress_status(url, id, action){

    $.post(
        site_url+url,
        {'action':action,
         'id':id},
        function (resp) {            
            if(resp!='error'){
                if(!resp){
                    //alert(resp);
                }
                if(resp != null && resp.processed>0){
	               var processed = resp.processed;
	                var total_rows = resp.num_rows;
	                var percent_complete = Math.ceil((resp.processed/resp.num_rows)*100);
	                var progress_length = percent_complete*3;
	                $('div.progressBar').width(progress_length);
	                $('#percents').html(percent_complete+'%');
	                $('#progress_info').html(processed+' from '+total_rows);
	                if(total_rows == processed){
	                    clearTimeout(progress_timeout_id);
	                    $('div.progressBar').html('Processing is completed!');
                            $('#submit_file').show();
                            window.location.href=window.location.href;
	                }
                }
            }else{
                clearTimeout(progress_timeout_id);
            }
        },
        'json'
    )
    progress_timeout_id = setTimeout("show_progress_status('"+url+"', '"+id+"', 'get_price_upload_status')", 500);
}

function checkURL(value) {
  var urlregex = new RegExp(
        "^(http:\/\/|http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
  if(urlregex.test(value)) {
    return true;
  }
  return false;
}
function init_ajax_data_form(data_form) {
    
    var is_profiles_page = window.location.pathname == '/profiles.php';
    if(is_profiles_page){
         var action_url = site_url+'profiles.php';
    }else if (window.location.pathname == '/customers_info.php'){
         var action_url = site_url+'customers_info.php';
    }else if (window.location.pathname == '/missing_records_sessions.php'){
         var action_url = site_url+'/missing_records_sessions.php';
    }else{
        var action_url = site_url+'profile_details.php';
    }    

	var form_name = $(data_form).attr('name');
	var data_filter = $('#'+form_name+'_filter').get(0);
	var data_table = $('#'+form_name+'_data').get(0);
	var data_paging = $('#'+form_name+'_paging').get(0);

         if (form_name == 'missing_records_sessions'){
            bindAttendeSessionLinksClickHandler();
        }

	if(data_filter) {
		$('#'+form_name+'_apply').unbind('click');
		$('#'+form_name+'_apply').click(function(e){
			$('#div-loader').show();
			e.preventDefault();
			var form_values = $(data_form).serialize();
                        $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            url: action_url,
                            data: {'action':'apply_filter',
                                  'called_from':form_name,
				  'filter_data':form_values },
                            timeout: 5000,
                            success: function(data, textStatus ){
                                        $(data_paging).replaceWith(data.pager_html);
					$(data_table).replaceWith(data.data_html);
					init_ajax_data_form(data_form);
                                        bindDeleteProfileLinkClickHandler();
					$('#div-loader').hide();
                            },
                            error: function(xhr, textStatus, errorThrown){
                              $('#div-loader').hide();
                              location.reload();
                            }
                          })

		})
		$('#'+form_name+'_reset').unbind('click');
		$('#'+form_name+'_reset').click(function(e){
			$('#div-loader').show();
			clear_inputs(data_filter);
			e.preventDefault();
			var form_values = $(data_form).serialize();
			$.post(
				action_url,
				{'action':'reset_filter',
                                 'called_from':form_name,
                                'filter_data':form_values},
				function (resp) {
					$(data_table).replaceWith(resp.data_html);
					if(data_paging){
						$(data_paging).replaceWith(resp.pager_html);
					}
					init_ajax_data_form(data_form);
                                        bindDeleteProfileLinkClickHandler();
					$('#div-loader').hide();
				},
				'json'
			)
		})

	}

	if(data_table) {
                var tr_headings = $(data_table).children('tr').get(0)?$(data_table).children('tr').get(0):$(data_table).children('tbody').children('tr').get(0);
		$(tr_headings).children('th').children('a.sort_link').each(function(){
			var sort_direction = $(this).hasClass('asc')?'desc':'asc';
                        var sort_field = $(this).attr('rel');
			$(this).unbind('click');
			$(this).click(function(){
				$('#div-loader').show();
				$.post(
					action_url,
					{'action':'sort',
                                         'sort_field':sort_field,
                                         'sort_direction':sort_direction,
                                         'called_from':form_name},
					function (resp) {
						$(data_paging).replaceWith(resp.pager_html);
						$(data_table).replaceWith(resp.data_html);
						init_ajax_data_form(data_form);
                                                bindDeleteProfileLinkClickHandler();
						$('#div-loader').hide();
					},
					'json'
				);
				return false;
			})
		})

                if (form_name == 'assignments'){
                     $("input[name='assignment_type']:radio").unbind('click');
                    $("input[name='assignment_type']:radio").click(function(){

                        var profile_id = $('#profile_id').val();                      
                        
                        $('#div-loader').show();
                        $.post(
                                action_url,
                                {'action':'get_page',
                                 'profile_id':profile_id,
                                 'assignment_type':$(this).val(),
                                 'called_from':form_name,
                                 'page':0},
                                function (resp) {
                                        $(data_paging).replaceWith(resp.pager_html);
                                        $(data_table).replaceWith(resp.data_html);
                                        init_ajax_data_form(data_form);
                                        $('#div-loader').hide();
                                },
                                'json'
                        );
                    })
                }
               
                if (form_name == 'customers_info' || form_name == 'missing_records_sessions'){
                     $('#'+form_name+'_data .remove_items').unbind('click');
                     $('#'+form_name+'_data .remove_items').click(function(){

                        var selectedProfiles = new Array();                       
                        $("input.item_check[@name='lists[]']:checked").each(function() {
                            selectedProfiles.push($(this).val());
                        });

                        if (selectedProfiles.length == 0){
                            alert('Please select items to remove first!');
                            return false;
                        }

                        var ids = selectedProfiles.join(',');

                        $('#div-loader').show();
                        $.post(
                            action_url,
                            {'action':'remove',
                             'ids':ids,
                             'called_from':form_name
                            },
                            function (resp) {
                                $('#div-loader').hide();
                                if (resp.error){
                                    alert(resp.error);
                                }else{
                                    $(data_paging).replaceWith(resp.pager_html);
                                    $(data_table).replaceWith(resp.data_html);
                                    init_ajax_data_form(data_form);

                                    if (form_name == 'missing_records_sessions'){
                                        bindAttendeSessionLinksClickHandler();
                                    }
                                }  
                            },
                            'json'
                        );
                    })
                }
               

               $('#'+form_name+'_data .profile_check_all').unbind('click');

		$('#'+form_name+'_data .profile_check_all').click(function(){
			if($(this).hasClass('checked')){
				$('#'+form_name+'_data input[type=checkbox]').removeAttr('checked');
				$(this).removeClass('checked');
			} else {
				$('#'+form_name+'_data input[type=checkbox]').attr('checked',true);
				$(this).addClass('checked');
			}
		})

                $('#'+form_name+'_data .assign_to').unbind('click');
                $('#'+form_name+'_data .assign_to').click(function(){

                    var assign_action = $('#'+form_name+'_assign_action').val();
                    if (assign_action == 0){
                        assign_action = $('#'+form_name+'_assign_action2').val();
                        if (assign_action == 0){
                            alert('Please select action!');
                            return false;
                        }
                    }                   

                    var items_selected = $('#'+form_name+'_data input.item_check:checkbox:checked').length;
                    if(items_selected == 0){
                        alert('Please select items to assign first');
                        return false;
                    }

            var profile_id = '';
            if(is_profiles_page){
                var selectedProfiles = new Array();
                $("input.profile_check[@name='lists[]']:checked").each(function() {
                    selectedProfiles.push($(this).val());
                });

                if (selectedProfiles.length == 0){
                    alert('Please select profiles to assign!');
                    return false;
                }

                profile_id = selectedProfiles.join(',');

            }else{
                profile_id = $('#profile_id').val();
            }
                    var params = $(data_form).serialize();

                    $('#div-loader').show();
                    $.post(
                            action_url,
                            {'action':'assign',
                             'profile_id':profile_id,
                             'params':params,
                             'called_from':form_name
                            },
                            function (resp){
                                    $('#div-loader').hide();
                                    if(resp.errors){
                                            var error = '';
                                            $(resp.errors).each(function(k,v){
                                                    error += v+'\n';
                                            })
                                            alert(error);
                                    }

                                    if(resp.need_to_reload){
                                            window.location.reload();
                                    }                                    
                            },
                            'json'
                    );
                })

                $('#'+form_name+'_data .remove_assignment').unbind('click');
		$('#'+form_name+'_data .remove_assignment').click(function(){

                    var assign_action = $('#remove_action').val();
                    if (assign_action == 0){
                        assign_action = $('#remove_action2').val();
                        if (assign_action == 0){
                            alert('Please select action!');
                            return false;
                        }
                    }

                    var items_selected = $('#'+form_name+'_data input.item_check:checkbox:checked').length;
                    if(items_selected == 0){
                        alert('Please select assignment to remove first');
                        return false;
                    }

                    var profile_id = $('#profile_id').val();
                    var assignment_type = $("input[name='assignment_type']:checked").val();
                    var params = $(data_form).serialize();

                    $('#div-loader').show();
                    $.post(
                            action_url,
                            {'action':'remove',
                             'profile_id':profile_id,
                             'assignment_type':assignment_type,
                             'params':params,
                             'called_from':form_name
                            },
                            function (resp) {
                                    $(data_paging).replaceWith(resp.pager_html);
                                    $(data_table).replaceWith(resp.data_html);
                                    init_ajax_data_form(data_form);
                                    $('#div-loader').hide();
                            },
                            'json'
                    );
                })
	}

	if(data_paging) {		
		$(data_paging).children('a').each(function(){

			$(this).click(function(){
                             var profile_id = (is_profiles_page)?'':$('#profile_id').val();

                             var assignment_type = $("input[name='assignment_type']:checked").val();                            

				$('#div-loader').show();
				$.post(
					action_url,
                                        {'action':'get_page',
                                         'profile_id':profile_id,
                                         'assignment_type':assignment_type,
                                         'called_from':form_name,
                                         'page':$(this).attr('rel')},
					function (resp) {
						$(data_paging).replaceWith(resp.pager_html);
						$(data_table).replaceWith(resp.data_html);
						init_ajax_data_form(data_form);
                                                bindDeleteProfileLinkClickHandler();
						$('#div-loader').hide();
					},
					'json'
				);
				return false;
			})
		});
	}
}

function clear_inputs(selector){
	var selector_id = $(selector).attr('id');
	$('#'+selector_id+' input[type="text"]').val('');
}
function bindProfileActionLinksClickHandler(){
     bindProfileActionDownLinksClickHandler();
     bindProfileActionUpLinksClickHandler();

    // First unbind handler
    jQuery(".delete_action_link").unbind('click');

    jQuery(".delete_action_link").click(function(){
        var link = jQuery(this);
        var profile_id = link.attr('profile_id');
        var action_id = link.attr('action_id');

        var result = confirm('Are you sure you want to delete profile action?');
        if(result == false){
            return;
        }

        jQuery('#div-loader').show();

        jQuery.post(
            site_url+'profile.php',
            {
                'action':'delete',
                'profile_id':profile_id,
                'action_id':action_id
            },
            function (resp) {
                $('#div-loader').hide();
                if(resp.errors){
                        var error = '';
                        $(resp.errors).each(function(k,v){
                                error += v+'\n';
                        })
                        alert(error);
                }

                $("#profile_actions").replaceWith(resp.data_html);
                bindProfileActionLinksClickHandler();               
                bindAddProfileActions();
                bindSendProfileCopy();
            },
            "json"
            );
    });
}
function bindProfileActionDownLinksClickHandler(){

    jQuery(".down_action_link").unbind('click');
    jQuery(".down_action_link").click(function(){
        var link = jQuery(this);
        var profile_id = link.attr('profile_id');
        var action_id = link.attr('action_id');

        jQuery('#div-loader').show();

        jQuery.post(
            site_url+'profile.php',
            {
                'action':'action_down',
                'profile_id':profile_id,
                'action_id':action_id
            },
            function (resp) {
                $('#div-loader').hide();
                if(resp.errors){
                        var error = '';
                        $(resp.errors).each(function(k,v){
                                error += v+'\n';
                        })
                        alert(error);
                }

                $("#profile_actions").replaceWith(resp.data_html);
                bindProfileActionLinksClickHandler();
                bindAddProfileActions();
                bindSendProfileCopy();
            },
            "json"
            );
    });
}
function bindProfileActionUpLinksClickHandler(){
    jQuery(".up_action_link").unbind('click');
    jQuery(".up_action_link").click(function(){
        var link = jQuery(this);
        var profile_id = link.attr('profile_id');
        var action_id = link.attr('action_id');

        jQuery('#div-loader').show();

        jQuery.post(
            site_url+'profile.php',
            {
                'action':'action_up',
                'profile_id':profile_id,
                'action_id':action_id
            },
            function (resp) {
                $('#div-loader').hide();
                if(resp.errors){
                        var error = '';
                        $(resp.errors).each(function(k,v){
                                error += v+'\n';
                        })
                        alert(error);
                }

                $("#profile_actions").replaceWith(resp.data_html);
                bindProfileActionLinksClickHandler();
                bindAddProfileActions();
                bindSendProfileCopy();
            },
            "json"
            );
    });
}
function bindAddProfileActions(){
    $('.add_action_to_profile').unbind('click');
    $('.add_action_to_profile').click(function(){

        $('#submit_action').val('add_action');
        $('#add_profile_form').submit();
    })
}
function bindSendProfileCopy(){
    $('#save_profile_copy').unbind('click');
    $('#save_profile_copy').click(function(){

        $('#submit_action').val('save_copy');
        $('#add_profile_form').submit();
    })
}
function bindDeleteDMPLinksClickHandler(){

    // First unbind handler
    jQuery(".deletedmplink").unbind('click');
    jQuery(".deletedmplink").click(function(){
        var link = jQuery(this);
        var profile_id = link.attr('profile_id');

        var result = confirm('Are you sure you want to delete profile action?');
        if(result == false){
            return;
        }
        jQuery('#div-loader').show();

        jQuery.post(
            site_url+'dmps.php',
            {
                'action':'delete',
                'profile_id':profile_id
            },
            function (resp) {
                $('#div-loader').hide();
                if(resp.errors){
                        var error = '';
                        $(resp.errors).each(function(k,v){
                                error += v+'\n';
                        })
                        alert(error);
                }

                $("#dmps_container").replaceWith(resp.data_html);
                bindDeleteDMPLinksClickHandler();
            },
            "json"
            );
    });
}
function bindAssignProfilesTo(){
    $("input[name='assign_profiles_to']:radio").click(function(){
        var val = $(this).val();
        if (val == 1){
            $("#users_to_assign").show();
            $("#groups_to_assign").hide();
        }else{
            $("#users_to_assign").hide();
            $("#groups_to_assign").show();
        }
    });
}
function bindItemsDatabaseTables(){
    if($('.item_database_tables').get(0)){
        $(".item_database_tables").unbind('change');
        $('.item_database_tables').live('change',function(){

            var noaction = $(this).attr('noaction');
            if(!noaction){
            var onlylookupfield = $(this).attr('onlylookupfield');

            if (onlylookupfield  == '1'){
                var databases = $('#items_databases_for_row');
                var tables = $('#item_database_tables_for_row');
            }else{
                var databases = $('#items_databases');
                var tables = $('#item_database_tables');
            }

            var database = databases.val();
            var table = tables.val();

            jQuery('#div-loader').show();

            jQuery.post(
                site_url+'profile_action.php',
                {
                    'action':'get_table_fields',
                    'database':database,
                    'table':table,
                    'onlylookupfield':onlylookupfield
                },
                function (resp) {
                    $('#div-loader').hide();
                    if(resp.errors){
                        var error = '';
                        $(resp.errors).each(function(k,v){
                            error += v+'\n';
                        })
                        alert(error);
                    }

                    if (resp.onlylookupfield == '1'){
                        var lookup_fields = $("#db_get_row_block_lookup_fields");
                        lookup_fields.replaceWith(resp.lookup_fields_html);
                        lookup_fields.show();
                    }else{
                        var lookup_fields = $("#db_get_value_block_lookup_fields");
                        lookup_fields.replaceWith(resp.lookup_fields_html);
                        lookup_fields.show();

                        var get_fields = $("#db_get_value_block_get_fields");
                        get_fields.replaceWith(resp.get_fields_html);
                        get_fields.show();
                    }
                },
                "json"
                );
            }
            return true;
        })
    }
}
function bindAttendeSessionLinksClickHandler(){
    jQuery(".sessionlink").unbind('click');
    jQuery(".sessionlink").click(function(){
        var link = jQuery(this);
        var session_id = link.attr('session_id');
        var session_action = link.attr('session_action');

        var confirm_message = (session_action=='delete')?'Are you sure you want to delete session?':'Are you sure you want to restore session?\nCurrent session will be closed.';
        var result = confirm(confirm_message);
        if(result == false){
            return;
        }
        jQuery('#div-loader').show();
        jQuery.post(
            site_url+'missing_records_sessions.php',
            {
                'action':session_action,
                'id':session_id
            },
            function (resp) {
                $('#div-loader').hide();
                if(resp.errors){
                        var error = '';
                        $(resp.errors).each(function(k,v){
                                error += v+'\n';
                        })
                        alert(error);
                }

                $("#missing_records_sessions_data").replaceWith(resp.data_html);
                bindAttendeSessionLinksClickHandler();
            },
            "json"
            );
    });
}
function update_profile_list(){

    var group_id = $("#profile_selection").val();
    var platform = $('#profile_platform_selection').val();

    $('#div-loader').show();
    $.post(
        site_url+'profiles.php',
        {'action':'change_profiles',
         'group_id':group_id,
         'platform':platform},
             function (resp) {
                $('#div-loader').hide();
                if (resp.error){
                    var error_msg = $('#error_msg');
                    error_msg.html(resp.error);
                }else{
                    var profiles_container = $('#profiles_container');
                    profiles_container.html(resp.data);

                     $('.profiles_check_all').click(function(){
                        if($(this).hasClass('checked')){
                            $('input.profile_check[type=checkbox]').removeAttr('checked');
                            $(this).removeClass('checked');
                        }else {
                            $('input.profile_check[type=checkbox]').attr('checked',true);
                            $(this).addClass('checked');
                        }
                    });

                    bindDeleteProfileLinkClickHandler();

                    $(".assign_profile").click(assign_profile);
                    $(".remove_profile").click(remove_assigned_profile);

                    $.collapsible(".module .header");

                    if($('form.ajax_data').get(0)) {
                        $('form.ajax_data').each(function(){
                            init_ajax_data_form(this);
                        })
                    }

                    bindAssignProfilesTo();
                }
            },
            "json"
        );
}

