// AssociationWebSuite(tm) - application.js
// (c) 2006 TCS Software, Inc.

// Query Building...
// Adds the selected criteria to the query SQL line
var tcsAndOrSave = "AND";
var editorCursorPosition=0;

String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

String.prototype.ltrim=function(){
    return this.replace(/^\s*/g,'');
}

String.prototype.rtrim=function(){
    return this.replace(/\s*$/g,'');
}

// tcs_SubmitAjaxForm() does an Ajax form submission from within javascript
// see aws/Views/
function tcs_SubmitAjaxForm(url, form){
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, parameters:Form.serialize(document.forms[form])});
}

function tcsAddQueryLine(Action)  {
    // First, get the components of the line
    var build_query_form = document.build_query_form
    build_query_form.tcsSQLStmt.size = build_query_form.tcsSQLStmt.options.length;
    var sInputField = build_query_form.tcsFieldNames.options[build_query_form.tcsFieldNames.selectedIndex].value;
    if (build_query_form.tcsSave){
        var tcsAndOrSave = build_query_form.tcsSave.value;
    }
    if (build_query_form.tcsSearchCondition){
        var sCondition = build_query_form.tcsSearchCondition.options[build_query_form.tcsSearchCondition.selectedIndex].value;
    } else {
        var sCondition = '';
    }
    if (build_query_form.tcsSearchFor){
        var sValue = build_query_form.tcsSearchFor.value;
    } else {
        var sValue   = '';
    }
    if (build_query_form.tcsAndOr){
        var sAndOr = build_query_form.tcsAndOr.options[build_query_form.tcsAndOr.selectedIndex].value;
    } else {
        var sAndOr   = '';
        tcsAndOrSave =     '';
    }   

    if (build_query_form.tcsSortDirection){
        var sValue = build_query_form.tcsSortDirection.value;
    }
    if (build_query_form.tcsCommonSorts){
        var sCommonSort = build_query_form.tcsCommonSorts.value;
    } else {
        var sCommonSort = '';
    }
    
    if (sCommonSort != '') {
        var sort_items = sCommonSort.split('~')
        var sSortDirection = 'A';  // always assume ascending sort order for common sorts
        // Erase the 'None' line, if it exists
        if (build_query_form.tcsSQLStmt.size>0) {
            if (build_query_form.tcsSQLStmt.options[0].value == 'None') {
                build_query_form.tcsSQLStmt.options[0]=null;
            }
        }
        for (var i=0; i < sort_items.length; i++) {
            build_query_form.tcsSQLStmt.options[build_query_form.tcsSQLStmt.options.length] = new Option(sort_items[i] + ' [' + sSortDirection + ']');
        }
        // Resize the control to display all lines
        build_query_form.tcsSQLStmt.size=build_query_form.tcsSQLStmt.options.length;
        // Reposition the common sort order drop-down to none selected
        build_query_form.tcsCommonSorts.selectedIndex = 0;
        return;
    }
    if (sInputField == "") { return; }

    // Build the line
    var convert = tcsAndOrSave + ' ' + sInputField + ' ' + sCondition;
    if (sValue!='') {convert += ' [' + sValue + ']';}

    tcsAndOrSave = sAndOr;
    
    // Erase the 'None' line, if it exists
    if (build_query_form.tcsSQLStmt.size>0) {
        if (build_query_form.tcsSQLStmt.options[0].value == 'None') {
            build_query_form.tcsSQLStmt.options[0]=null;
        }
    }
    // Add a new line or replace the selected line
    if (Action == 1) {  // ADD LINE
        build_query_form.tcsSQLStmt.options[build_query_form.tcsSQLStmt.options.length] = new Option(convert,convert);
    }
    else { // REPLACE selected line (if is was selected)
        var iWhichOneSelected = build_query_form.tcsSQLStmt.selectedIndex;
        // If any line was selected...
        if (iWhichOneSelected>-1) {
                build_query_form.tcsSQLStmt.options[iWhichOneSelected].text = convert;
                build_query_form.tcsSQLStmt.options[iWhichOneSelected].value = convert;
                build_query_form.tcsSQLStmt.selectedIndex=iWhichOneSelected;
        } else { window.status = 'No line selected.'; }
    }
    // Resize the control to display all lines
    build_query_form.tcsSQLStmt.size=build_query_form.tcsSQLStmt.options.length;
    // Reposition the field select drop-down list to none selected
    build_query_form.tcsFieldNames.selectedIndex = 0;
}

// Adds common groups of fields
function tcsAddCommonGroups() {
    var build_query_form = document.build_query_form;
    var sCommonGroup = build_query_form.tcsCommonGroups.value;
    
    if (sCommonGroup != '') {
        var group_items = sCommonGroup.split('~')
        // Erase the 'None' line, if it exists
        if (build_query_form.tcsSQLStmt.options[0].value == 'None') {
            build_query_form.tcsSQLStmt.options[0]=null;
        }
        for (var i=0; i < group_items.length; i++) {
            build_query_form.tcsSQLStmt.options[build_query_form.tcsSQLStmt.options.length] = new Option(group_items[i]);
        }
        // Resize the control to display all lines
        build_query_form.tcsSQLStmt.size=build_query_form.tcsSQLStmt.options.length;
    }
}

// Deletes the selected line
function tcsDeleteQueryLine() {
	var build_query_form = document.build_query_form;
	var iWhichOneSelected = build_query_form.tcsSQLStmt.selectedIndex;
	// If any line was selected...
	if (iWhichOneSelected>-1) {
	   // If there's more than one line, then delete the selected line
	   if ((iWhichOneSelected>0) || (build_query_form.tcsSQLStmt.size>1)) {
	      build_query_form.tcsSQLStmt.options[iWhichOneSelected]=null;
	   }
	   else {  // The first line was selected, so just set it to 'None'
	      build_query_form.tcsSQLStmt.options[0].text='None';
		  build_query_form.tcsSQLStmt.options[0].value='None';
	   }
	 }
	 else {  // No line was selected
	 	var iNewLength = build_query_form.tcsSQLStmt.options.length;
		if (iNewLength>0) {  // If there's at least one line, then resize the control to the appropriate number of lines
	      build_query_form.tcsSQLStmt.size=build_query_form.import_rules.options.length;
	      }
	    else { // No lines, so add the first line back
		     build_query_form.tcsSQLStmt.options[0]=new Option('None','None');  }

	 }
	 // Resize the control to reflect the new number of lines
	 build_query_form.tcsSQLStmt.size=build_query_form.tcsSQLStmt.options.length;
	 // If the selected one is greater than the number of items in the control
	 // then select the last line of the SQL stmt
	 if (iWhichOneSelected>build_query_form.tcsSQLStmt.size-1) {iWhichOneSelected=build_query_form.tcsSQLStmt.size-1;}
	 // Selected the previous line (highlight it) above the one deleted
	 build_query_form.tcsSQLStmt.selectedIndex=iWhichOneSelected;
}

// Deletes all lines
function tcsDeleteQueryAll() {
    var build_query_form = document.build_query_form
    build_query_form.tcsSQLStmt.options.length=0;
    build_query_form.tcsSQLStmt.options[0]=new Option('None','None');
    build_query_form.tcsSQLStmt.size=build_query_form.tcsSQLStmt.options.length;
}

// Toggles AND/OR
function tcsQueryAndOrSwap() {
	var build_query_form = document.build_query_form;
	var iWhichOneSelected = build_query_form.tcsSQLStmt.selectedIndex;
	var sItem = build_query_form.tcsSQLStmt.options[iWhichOneSelected].value;

	if (sItem.substr(0,4) == 'AND ') {
		sItem = 'OR ' + sItem.substr(4);
	} else if (sItem.substr(0,3) == 'OR ') {
		sItem = 'AND ' + sItem.substr(3);
	} else {
		sItem = 'AND ' + sItem;
        }
	build_query_form.tcsSQLStmt.options[iWhichOneSelected].text = sItem;
	build_query_form.tcsSQLStmt.options[iWhichOneSelected].value = sItem;
}

// Moves line up or down
function tcsQueryMove(dir) {
	var build_query_form = document.build_query_form
	var iWhichOneSelected = build_query_form.tcsSQLStmt.selectedIndex;
	var convertSave;
	var convert;
	if (dir > 0) {                       // Move down
		if (iWhichOneSelected < build_query_form.tcsSQLStmt.options.length) {
			convert = build_query_form.tcsSQLStmt.options[iWhichOneSelected].value;
			convertSave = build_query_form.tcsSQLStmt.options[iWhichOneSelected + dir].value;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected].value = convertSave;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected].text = convertSave;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected+dir].value = convert;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected+dir].text = convert;
			build_query_form.tcsSQLStmt.selectedIndex += dir;
		}
	}else{
		if (iWhichOneSelected > 0) {	// Move up
			convert = build_query_form.tcsSQLStmt.options[iWhichOneSelected].value;
			convertSave = build_query_form.tcsSQLStmt.options[iWhichOneSelected + dir].value;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected].value = convertSave;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected].text = convertSave;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected+dir].value = convert;
			build_query_form.tcsSQLStmt.options[iWhichOneSelected+dir].text = convert;
			build_query_form.tcsSQLStmt.selectedIndex += dir;
		}
	}
}

// Select all items in the list on submit
function tcsSubmitQuery(WhichForm)  {
	var build_query_form = document.build_query_form

    if (WhichForm == 1) {
        var iWhichOneSelected = build_query_form.tcsSQLStmt.selectedIndex;
    
        if (build_query_form.tcsSQLStmt.options[0].value == 'None') {
          build_query_form.tcsSQLStmt.options[0].value = '';
          build_query_form.tcsSQLStmt.size = 0;
          }
    
        // Select all SQL stmt lines before submitting
        for (var iCtr=0; iCtr<build_query_form.tcsSQLStmt.size; iCtr++) {
          build_query_form.tcsSQLStmt.options[iCtr].selected = true;
          }
        return true;
    }
    if (WhichForm == 2) {
    }
    
}


// End of Query Building

// Inserts contact list placeholder into wysiwyg editor area
function tcsAddPlaceholder(editor_sequence_no,text_area_id) {
    var obj = document.forms[0].elements["contact_fields_list["+editor_sequence_no+"]"];
    var iWhichOneSelected = obj.selectedIndex;
    str = '$$' + obj.options[iWhichOneSelected].value + "$$";
    tcsInsertIntoEditor(text_area_id,str)
}

// Inserts contact list placeholder into input form area
function tcsAddPlaceholder_InputForms(editor_sequence_no,text_area_id) {
    var obj = document.forms[0].elements["contact_fields_list["+editor_sequence_no+"]"];
    var iWhichOneSelected = obj.selectedIndex;
    str = '$$' + obj.options[iWhichOneSelected].value + "$$";
    tcsInsertIntoEditor_InputForms(text_area_id,str)
}

// Inserts linkto directive into wysiwyg editor area
function tcsAddTcsLinkToDirective(element_id,element_type) {
    var selectedDirective = document.forms[0].tcslinkto_directives.selectedIndex;
    var directive = document.forms[0].tcslinkto_directives.options[selectedDirective].value.split('&')[0];
    if (directive.length == 0) {
        return;
    }
    directive = directive.split('=')[1];
    
    var elementObj = document.getElementById(element_id);
    var valid      = true;

    switch (element_type){
        case 'integer':
            valid = isInteger(elementObj.value);
        break;
        case 'string':
            valid = isString(elementObj.value);
        break;
    }
    
    if (elementObj.value.length > 0 && valid) {
        directive += '[' + elementObj.value
    } else {
        alert('Please specify a valid ' + element_id);
        elementObj.focus();
        elementObj.select();
        return;
    }

    var delim = ',';
    var linkedText = document.forms[0].linked_text.value;
    if (/,/i.test(linkedText)) { delim = '|'; }

    if (document.forms[0].linked_text) {
        if (linkedText.length > 0) { 
            directive += delim + linkedText;
        }
    }
    if (document.forms[0].tcslinkto_layout) {
        if (document.forms[0].tcslinkto_layout.type != 'hidden') {
            var selectedLayout    = document.forms[0].tcslinkto_layout.selectedIndex;
            var layout            = document.forms[0].tcslinkto_layout.options[selectedLayout].value;
            if (layout.length > 0) {
                if (!linkedText || linkedText.length == 0) { 
                    directive += delim;
                }
                directive += delim + layout
            }    
        }
    }
    if (document.forms[0].tcslinkto_target) {
        if (document.forms[0].tcslinkto_target.type != 'hidden') {
            var selectedTarget    = document.forms[0].tcslinkto_target.selectedIndex;
            var target            = document.forms[0].tcslinkto_target.options[selectedTarget].value;
            if (target.length > 0 && !/parent/i.test(target) ) {
                if (!layout || layout.length == 0) {
                    directive += delim;
                    if (!linkedText || linkedText.length == 0) {
                        directive += delim;
                    }
                }
                directive += delim + target
            }
        }
    }
    directive += ']'

    tcsInsertIntoEditor(0,directive)
    
}


// Inserts string into wysiwyg editor area
function tcsInsertIntoEditor(text_area_id,str) {
    if (editor_hidden) {
        var obj = document.getElementById(text_area_id);
        if (obj.selectionStart || obj.selectionStart == '0') {
            var startPos = obj.selectionStart;
            var endPos = obj.selectionEnd;
            obj.value = obj.value.substring(0, startPos)+ str + obj.value.substring(endPos, obj.value.length);
        } else {
            obj.value += str;
        } 
    } else {
        try {
            tinyMCE.execCommand('mceInsertContent', false, str);
        }
        catch (err) {
            txt="There was an error on this page.\n\n"
            txt+="Error description: " + err.description + "\n\n"
            txt+="Click OK to continue.\n\n"
            alert(txt)
        }
    }
}

// Inserts string into wysiwyg editor area
function tcsInsertIntoEditor_InputForms(text_area_id,str) {
        str = str + "\n";
        var obj = document.getElementById(text_area_id);
        if (obj.selectionStart || obj.selectionStart == '0') {
            var startPos = obj.selectionStart;
            var endPos = obj.selectionEnd;
            obj.value = obj.value.substring(0, startPos)+ str + obj.value.substring(endPos, obj.value.length);
        } else {
            obj.value += str;
        }
}


// Adds the import rule to the import definition
function tcsAddLine(Action)  {
	// First, get the components of the line
	var import_data_form = document.import_data_form
	var sInputField = import_data_form.contact_field_name.options[import_data_form.contact_field_name.selectedIndex].value;
	var sOutputField = import_data_form.contact_column_name.options[import_data_form.contact_column_name.selectedIndex].value;

	if ((sInputField == "") || (sOutputField == "")) { return; }
        
	if(tcsIsPhonetypeSelected(sOutputField)) {
            phone = sOutputField.split(':');
            obj=document.getElementById('contact_phone_type');
            sOutputField = obj.value + '.'  + phone[0] + ':' + phone[1];
            obj=document.getElementById('phone_type');
            obj.style.display = 'none';
        }

	if(tcsIsAddresstypeSelected(sOutputField)) {
            address = sOutputField.split(':');
            obj=document.getElementById('contact_address_type');
            sOutputField = obj.value + '.' + address[0] + ':' + address[1];
            obj=document.getElementById('address_type');
            obj.style.display = 'none';
        }

	if(tcsIsAttributeCategorySelected(sOutputField)) {
            obj=document.getElementById('attribute_category');
            obj.style.display = 'none';
        }

        var translate = import_data_form.import_action_do_translate.checked;
        var translation = import_data_form.import_config_translate.value;
        var to_upper = import_data_form.import_config_to_upper.checked;
        var to_proper = import_data_form.import_config_to_proper.checked;
        var to_numeric = import_data_form.import_config_to_numeric.checked;
        var to_us_phone = import_data_form.import_config_to_us_phone.checked;
        var to_clean_zip = import_data_form.import_config_to_clean_zip.checked;
        var to_name_fields = import_data_form.import_config_to_name_fields.checked;
        var four_digit_year_to_date = import_data_form.import_config_four_digit_year_to_date.checked;
        var encrypt_value = import_data_form.import_config_encrypt_value.checked;

        // build translation options
        var operations = '';
        if (translate) {
            if (to_upper) {
                if (operations != '')
                    operations += ','
                operations += 'to_upper';
            } 
            if (to_proper) {
                if (operations != '')
                    operations += ','
                operations += 'to_proper';
            } 
            if (to_numeric) {
                if (operations != '')
                    operations += ','
                operations += 'to_numeric';
            } 
            if (to_us_phone) {
                if (operations != '')
                    operations += ','
                operations += 'to_us_phone';
            } 
            if (to_clean_zip) {
                if (operations != '')
                    operations += ','
                operations += 'to_clean_zip';
            } 
            if (to_name_fields) {
                if (operations != '')
                    operations += ','
                operations += 'to_name_fields';
            }
            if (four_digit_year_to_date) {
                if (operations != '')
                    operations += ','
                operations += 'four_digit_year_to_date';
            }
            if (encrypt_value) {
                if (operations != '')
                    operations += ','
                operations += 'encrypt_value';
            }
            if (translation.length > 0) {
                translation = translation.replace(/,/g,'~');
                translation = translation.replace(/[\n\r]/g,',');
            }
            
            if (operations != '' || translation != '') {
                sOutputField += '['+operations+']'
                sOutputField += '['+translation+']'
            }
        }
        
	// Build the line
	var convert = sInputField + ' => ' + sOutputField;

	// Erase the 'None' line, if it exists
	if (import_data_form.import_rules.options.length > 0) {
            if (import_data_form.import_rules.options[0].value == 'None') {
                import_data_form.import_rules.options[0]=null;
	    }
	}
	// Add a new line or replace the selected line
	if (Action == 1) {  // ADD LINE
	   import_data_form.import_rules.options[import_data_form.import_rules.options.length] = new Option(convert,convert);
	   // Resize the control to display all lines
	   import_data_form.import_rules.size=import_data_form.import_rules.options.length;
        }
	else { // REPLACE selected line (if is was selected)
            var iWhichOneSelected = import_data_form.import_rules.selectedIndex;
	    // If any line was selected...
	    if (iWhichOneSelected>-1) {
			import_data_form.import_rules.options[iWhichOneSelected].text = convert;
			import_data_form.import_rules.options[iWhichOneSelected].value = convert;
			import_data_form.import_rules.selectedIndex=iWhichOneSelected;
            }
            else { window.status = 'No line selected.'; }
	}
}

// allows caller to break out of frame
function tcsBreakoutOfFrame()
{
    if (top.location != location) {
        top.location.href = document.location.href ;
    }
}

// checks resize for reasonable amount
function tcsCheckResize() {
	alert('in tcsCheckResize');
	return true;
}

//  --------------------------------------------------------------------
//  tcsShowIfPresent - checks the select element identified by select_id 
//  for the presence of an option matching the string target_value, if present
//  display the element identified by display_id, else hide same element
//  --------------------------------------------------------------------
function tcsShowIfPresent(select_id,target_value,display_id) {
    select_obj=document.getElementById(select_id);
    display_obj=document.getElementById(display_id);
    found = false;
    for (var i=0; i < select_obj.options.length; i++) {
        if (target_value == select_obj.options[i].value.trim()) {
            found = true;
            break;
        }
    }
    if (found) {
        Element.show(display_id);
    } else {
        Element.hide(display_id);
    }    
    
}

// Deletes the selected line
function tcsDeleteLine() {
	var import_data_form = document.import_data_form
	var iWhichOneSelected = import_data_form.import_rules.selectedIndex;
	// If any line was selected...
	if (iWhichOneSelected>-1) {
	   // If there's more than one line, then delete the selected line
	   if ((iWhichOneSelected>0) || (import_data_form.import_rules.size>1)) {
	      import_data_form.import_rules.options[iWhichOneSelected]=null;
	   }
	   else {  // The first line was selected, so just set it to 'None'
	      import_data_form.import_rules.options[0].text='None';
		  import_data_form.import_rules.options[0].value='None';
	   }
	 }
	 else {  // No line was selected
	 	var iNewLength = import_data_form.import_rules.options.length;
		if (iNewLength>0) {  // If there's at least one line, then resize the control to the appropriate number of lines
	      import_data_form.import_rules.size=import_data_form.import_rules.options.length;
	      }
	    else { // No lines, so add the first line back
		     import_data_form.import_rules.options[0]=new Option('None','None');  }

	 }
	 // Resize the control to reflect the new number of lines
	 import_data_form.import_rules.size=import_data_form.import_rules.options.length;
	 // If the selected one is greater than the number of items in the control
	 // then select the last line of the SQL stmt
	 if (iWhichOneSelected>import_data_form.import_rules.size-1) {iWhichOneSelected=import_data_form.import_rules.size-1;}
	 // Selected the previous line (highlight it) above the one deleted
	 import_data_form.import_rules.selectedIndex=iWhichOneSelected;
}

// Deletes all lines
function tcsDeleteAll() {
    var import_data_form = document.import_data_form
    import_data_form.import_rules.options.length=0;
    import_data_form.import_rules.options[0]=new Option('None','None');
    import_data_form.import_rules.size=import_data_form.import_rules.options.length;
}

// Hides DOM element by id
function tcsHide(id) {
    Element.hide(id);
}

// Displays DOM element by id
function tcsShow(id) {
    Element.show(id);
}

// Toggles display of DOM element by id
function tcsToggle(id) {
    Element.toggle(id);
}

// Erase text
function tcsErase(id) {
    obj=document.getElementById(id);
    obj.value = '';
}

// select all items
function tcsSelectAll(id) {
    // Select all SQL stmt lines before submitting
    obj=document.getElementById(id);
    for (var iCtr=0; iCtr < obj.options.length; iCtr++) {
        obj.options[iCtr].selected = true;
    }
}

// Inserts the TCSGALLERY directive
function tcsGallery() {
    var form   = document.forms['gallery_form'];
    var search = form.asset_search_for.value;
    var cols   = form.asset_columns.value;
    var rows   = form.asset_rows.value;
	var style = form.asset_gallery_style.value;
	var include_titles = '0';
	var include_descriptions = '0';
	var include_borders = '0';

	if (form.asset_include_titles.checked) {
			include_titles = '1';
		}
	if (form.asset_include_descriptions.checked) {
			include_descriptions = '1';
		}
	if (form.asset_include_borders.checked) {
			include_borders = '1';
		}
	if (!isInteger(cols)){alert('Columns must contain a numeric value'); return(false);}
	if (!isInteger(rows)){alert('Rows must contain a numeric value'); return(false);}
    var gallery = 'TCSGALLERY["'+search+'",'+rows+','+cols+','+style+','+include_titles+','+include_descriptions+','+include_borders+']';
    tinyMCE.execCommand('mceInsertContent', false, gallery);
	parent.messageObj.close();
	return(false);
}

// Inserts the TCSSLIDESHOW directive
function tcsSlideShow() {
    var form   = document.forms['gallery_form'];
    var search = form.search_for.value;
    var style  = form.style.value;
    var size   = form.image_size.value;
    
    var width  = 700;
    var height = 450;
    if (size==50) { width = 350; height = 293; }
    if (size==33) { width = 234; height = 202; }
    if (size==10) { width = 133; height = 133; }
    
    var include_titles = '0';
    var include_descriptions = '0';
    var include_copyrights = '0';
    var include_carousel = '0';  /* now obsolete */
    var randomize_images = '0';
    var float_captions   = '0';
    var carousel_label = '';  /* now obsolete */
    var info_zone_height = form.info_zone_height.value;
    
    var info_title_size = '90';   /* font-size percent */
    var info_description_size = '75'; /* font-size percent */
    var slide_timer_delay = 5; /* seconds */
    var background_color = '';
    var transition_effect = 'fade';
    var max_images = form.max_images.value;

    if (form.include_titles.checked) { include_titles = '1'; }
    if (form.include_descriptions.checked) { include_descriptions = '1'; }
    if (form.include_copyrights.checked) { include_copyrights = '1'; }
    if (form.randomize_images.checked) { randomize_images = '1'; }
    if (form.float_captions.checked) { float_captions = '1'; }

    var gallery = 'TCSSLIDESHOW2["'+search+'",'+style+','+size+','+width+','+height+','+include_titles+','+include_descriptions+','+include_copyrights+','+include_carousel+','+carousel_label+','+info_zone_height+','+info_title_size+','+info_description_size+','+slide_timer_delay+','+background_color+','+randomize_images+','+transition_effect+','+float_captions+','+max_images+']';
    tinyMCE.execCommand('mceInsertContent', false, gallery);
    parent.messageObj.close();
    return false;
}

// Manages Insert Photo popup
function tcsInsertPhoto() {
  
var photoForm = document.forms['photo_form'];
    var size = photoForm.asset_size.value;
	var border = '0';
	var id = photoForm.asset_id.value;
	var position = photoForm.asset_position.value;
	var title = photoForm.asset_title.value;
        var org_id = photoForm.org_id.value;
        var host = photoForm.host.value;
	var wrap = '';
	var unwrap = '';
	var window = '';
        var image_link = '';
        var image_style_class = '';
        
        // if position is left or right-justify, then add a class to the image tag
        if (position == 'LEFT') {
            image_style_class = ' class="imgleft" align="left" ';
        } 
        if (position == 'RIGHT') {
            image_style_class = ' class="imgright" align="right" ';
        } 
    
	if (photoForm.asset_include_borders.checked) {
			border = '1';
		}
	if (photoForm.asset_new_window.checked) {
			window = 'target="_blank"';
		}
	var misc = ' alt="'+title+'" border="'+border+ '" ' + image_style_class;
        var url = 'http://'+host+'/aws/'+org_id;
	if (size == 'T') {
		image_link = '<img src='+url+'/asset_manager/get_icon/'+id + misc + '>';
		}
        if (size == 'S') {
            image_link = '<img src='+url+'/asset_manager/get_image_small/'+id + misc + '>';
            }
        if (size == 'M') {
            image_link = '<img src='+url+'/asset_manager/get_image_medium/'+id + misc + '>';
            }
        if (size == 'F') {
		image_link = '<img src='+url+'/asset_manager/get_image/'+id + misc + '>';
		}
        
	if (photoForm.asset_url.value != '') {
		wrap = '<a href="'+photoForm.asset_url.value+'" '+window+'>';
		unwrap = '</a>';
	}
	photoForm.asset_url.value = '';
	image_link = wrap + image_link + unwrap;
	
        // If position is centered, then we need to drop image within a div tag
        // with the class of 'imgcenter'
        if (position == 'CENTER') {
            image_link = '<span class="imgcenter">' + image_link + '</span>';   
        }
    
    try {
        if (editorCursorPosition) {
            tinyMCE.selectedInstance.selection.moveToBookmark(editorCursorPosition);
        }
        tinyMCE.execCommand('mceInsertContent', false, image_link);
        editorCursorPosition = 0;
    }
    catch (err) {
        txt="There was an error on this page.\n\n"
        txt+="Error description: " + err.description + "\n\n"
        txt+="Click OK to continue.\n\n"
        alert(txt)
    }
	parent.messageObj.close();
        tcs_scrollTo('FindAssets');
        return false;
        
}

function tcsValidateInput(form) {
    var field_key = document.getElementById('contact_no_field_name')
    var update_existing = document.getElementById('update_existing_records_div').style.display == 'block' ? true : false
    
    if (update_existing) {
        if (field_key.selectedIndex < 0) {
            alert("Update existing records selected.  Please either select a source primary key field to use in updating records or return to previous form and de-select the 'Update existing contacts' checkbox.")
            field_key.focus();
            return false;
        }
    }
    
}

function tcsSubmitForm(WhichForm)  {
    var import_data_form = document.import_data_form

    if (WhichForm==1) {
        // Was a merge file specified?
        var obj=document.getElementById('contact_tmp_data');
        var sValue = obj.value;
        if (sValue.length==0)	{
            alert('Please specify an upload filename.');
            obj.focus();
            obj.select();
            return false;
        } else {
            if(/MSIE/.test(navigator.userAgent)){
                var RE = /\s/;
                if (sValue.match(RE))	{
                    obj.focus();
                    obj.select();
                    return false;
                } 
            }
            return true;
        }

    } // if (WhichForm==1)

    if (WhichForm==2) {

        if (import_data_form.import_rules.options[0].value == 'None') {
            alert('You must specify an import definition before continuing.');
            import_data_form.import_rules.focus();
            return false;
        }

        // Select all SQL stmt lines before submitting
        for (var iCtr=0; iCtr < import_data_form.import_rules.options.length; iCtr++) {
            import_data_form.import_rules.options[iCtr].selected = true;
        }
        return true;

    } // if (WhichForm==2)

}

// Have a look at selected Contacts column name, if Phone[0-9], then
//		ask for a phone type
function tcsSelected() {
    var selected = document.import_data_form.contact_column_name.value;

    obj_phone_type = document.getElementById('phone_type');
    obj_address_type = document.getElementById('address_type');
    obj_attribute_category = document.getElementById('attribute_category');

    obj_phone_type.style.display = "none";
    obj_address_type.style.display = "none";
    obj_attribute_category.style.display = "none";

    if(tcsIsPhonetypeSelected(selected)) {
        obj_phone_type.style.display = "block";
    } else if(tcsIsAddresstypeSelected(selected)) {
        obj_address_type.style.display = "block";
    } else if(tcsIsAttributeCategorySelected(selected)) {
        obj_attribute_category.style.display = "block";
    }
}

function tcsIsPhonetypeSelected(selected) {
    if(selected.match(/phone[0-9]/i)) {
        return true
    } else {
        return false
    }
}

function tcsIsAddresstypeSelected(selected) {
    if(selected.match(/:1/)) {
        return true
    } else {
        return false
    }
}

function tcsIsAttributeCategorySelected(selected) {
    if(selected.match(/:2/)) {
        return true
    } else {
        return false
    }
}

function tcsVerifySave(definition,definitionList) {
    var defn = document.getElementById(definition);
    var list = document.getElementById(definitionList);

    var svalue = defn.value;
    if (svalue.length == 0) {
        alert('Please specify an definition name.');
        defn.focus();
        defn.select();
        return false;
    }
    
    for (var i=0; i < list.options.length; i++) {
        if (svalue == list.options[i].value) {
            var rsp = confirm('This definition name already exists. Do you want to overwrite the existing definition?');
            if (rsp == true) {
                return true;
            } else {
                defn.focus();
                defn.select();
                return false;
            }
        }
    }
    return true
}

// test for legitimate email address
function testEmailAddress(addr) {
	var emailchar=/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
	// if the address contains < .. > check only what's between the brackets
	lb = addr.indexOf('<')
	rb = addr.indexOf('>')
	if ((lb>-1) && (rb>-1)) {
		return addr.substr(lb+1, rb-lb-1).match(emailchar);
	}else{
		return addr.match(emailchar);
	}
}

function isBadEmailAddr(addr){
	var test;
	if (addr && addr.value.length > 0) {
            addr.value = addr.value.replace("\r","");
            test = addr.value.split('\n');
            for (i = 0; i < test.length; i++) {
                    test[i] = test[i].replace('\r','');
                    if (test[i].length>0 && !testEmailAddress(test[i])) {
                            alert('Invalid email address: "'+test[i]+'"');
                            addr.focus();
                            addr.select();
                            return true;
                    }
            }
        } else {
            alert('Please enter a valid email address.');
            return true;
        }
	return false;
}
// tests email parms OK=true
function testEmailParms(model) {
	var from = document.getElementById(model + '_from_address');
	var addr = document.getElementById(model + '_email_address');
	var subj = document.getElementById(model + '_email_subject');
	var bcc = document.getElementById(model + '_email_bcc');
	var cc = document.getElementById(model + '_email_cc');

	if (from && from.value.length == 0) {
		alert('Please specify a \'From\' email address.');
		from.focus();
		from.select();
		return false;
	}
	if (addr && addr.value.length == 0) {
		alert('Please specify a \'To\' email address.');
		addr.focus();
		addr.select();
		return false;
	}
	if (subj && subj.value.length == 0) {
		alert('Please specify a Subject for this message.');
		subj.focus();
		subj.select();
		return false;
	}
	if (isBadEmailAddr(addr)) {
		addr.focus();
		addr.select();
		return false;
	}
	return true;
}
// Gets email parameters and sends the page via email
function tcsSendPage(form)
{
	var text = form.asset_email_text.value;
	if (!testEmailParms('asset')) {
		return false;
	}
	obj = document.getElementById('tcsEmail');
	if (obj) {
		obj.style.display = "none";
	}
		text = '<p>'+text.replace(/\n/g,'<br />')+'</p><p>------------------</p><p>&nbsp;</p>\n'+document.documentElement.innerHTML;
	if (obj) {
		obj.style.display = "block";
	}
	//alert(text);
	//tcsEmptyDiv('tcsEmail');
	form.asset_email_text.value = text;
	return true ;
}

// tcsEmptyDiv() sets a <div> block contents to blank
function tcsEmptyDiv(div) {
    var divCollection = document.getElementsByTagName("div");
    for (var i=0; i<divCollection.length; i++) {
        if(divCollection[i].getAttribute("id") == div) {
                divCollection[i].innerHTML = '';
        }
    }
}

 // Returns the page title to the caller
function tcsGetPageTitle(form,field)
{
	document.form.field.value = window.title
}

// Checks file size of files to be uploaded against max
function chkFileSize(max)
{
	var filename = document.upload_form.asset_tmp_file.value;
	var tag1 = document.upload_form.asset_tag1.value;
    var title = document.upload_form.asset_title.value;	
	var f_tag1 = document.upload_form.asset_file_tag1.value;
  if (title == '') {
	 alert('Please specify a Title.');
	 return(false);
  }
  if (filename == '') {
	 alert('No Filename was specified.');
	 return(false);
  }
  if ((tag1 == '') && (f_tag1 == '')) {
	alert('At least one search tag must be specified.');
	var n = document.upload_form.asset_tag1.length;
	if (n > 0) {
		document.upload_form.asset_tag1.focus();
	}else{
		document.upload_form.asset_file_tag1.focus();
	}
	return(false);
  }
  var ext = filename.split('.');
  var n = ext.length;
  if ((ext[n-1] == 'jpg')||(ext[n-1] == 'jpeg')||(ext[n-1] == 'gif')||(ext[n-1] == 'tif')) {
	/* OK, this is an image file, set the type selection */
	document.upload_form.asset_file_unzip.selected = true;
  }
  
  /* display progress indicator */
  document.getElementById('tcsProgress').style.display='block';
  
  return(true);
}

// validates the entry is a number
function isInteger(sText) {
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
	if (sText == '') {return false;}

   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   }
   
  function isString(a) {
      return typeof a == 'string';
  }

  function tcs_scrollTo(id) {
    var el = document.getElementById(id);
    el.scrollIntoView(true);
    }

    // The function called by MCE on "blur"
    function tinyMCE_onBlurCallback() {
        // Aparently this is only needed for IE, and seems to give bugs when used if FF
        if (editorCursorPosition == 0 && tinyMCE.isMSIE) {
            editorCursorPosition = tinyMCE.selectedInstance.selection.getBookmark(false);
        }
    }

// this chunk of code has been added in order to observe a pagination click and to show the
// progress element when it is
// see reference: http://wiki.github.com/mislav/will_paginate/ajax-pagination
document.observe("dom:loaded", function() {
  // the element in which we will observe all clicks and capture
  // ones originating from pagination links
  var container = $(document.body)

  if (container) {
    container.observe('click', function(e) {
      var el = e.element()
      if (el.match('.pagination a')) {
        Element.show('tcsProgress_page')
        new Ajax.Request(el.href, { method: 'get' })
        e.stop()
      }
    })
  }
})
