/**
 * Events
 */
$('input#search_keywords').keydown(function(event) {
	if(event.keyCode == 8) {
		if(this.value.length == 1 || this.value.length == 0) {
			$('#b_search_list').hide();
		}
	}
});

$('input#search_keywords').keyup(function() {
	var key = replaceSpaces(this.value);
	if(key.length != 0) {
		
		$('#b_search_list_i').html('');
		
	    var new_tags = getTagsListByKey(key);
	    
		setTags(new_tags, key);
	} 
});

$('input#search_keywords').blur(function(e) {
	if(this.value.length == 0) {
		$('#cross').click();
	}	
});

$('input#search_keywords').focus(function(e) {
	$('#search_keywords').attr('value', '');
	$('#cross').show();
});

$('input#search_keywords').click(function() {
	$('#tagTitleClassic').attr('title', $('#tagTitleClassic').html());
	$(this).attr('value', '');
	$('#cross').show();
});

$('#cross').click(function() {
	$('#b_search_list').hide();
	$(this).hide();
	$('#search_keywords').attr('value', $('#search_keywords').attr('title'));
	//clickTagClassic(getTagIdByTitle($('#tagTitleClassic').attr('title')), false, false);
});

function replaceSpaces( e ) {
    var template = /^\s+/;
    var rc = '';
    if(template.test(e)) {
        do {
            rc = e.replace(template, '');
        } 
        while(template.test(rc))
        return rc;
     }
    return e;     
}

function getTagIdByTitle(title) {
	var tagLen = tags.length;
    if($.browser.msie) {
    	tagLen--; 
    }
	for(var i = 0; i != tagLen; i++) {
		if(tags[i].title.toLowerCase() == title.toLowerCase()) {
			return tags[i].id;
			break;
		}
	}
	return false;
}
/**
 * 
 * @param str
 * @param allowed_tags
 * @return
 */
function strip_tags (str, allowed_tags) {
    var key = '', allowed = false;
    var matches = [];    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = ''; 
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
     // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }
     str += '';
 
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
     // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;        }
 
        // Save HTML tag
        html = matches[key].toString();
         // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {                allowed = true;
                break;
            }
        }
         if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
     return str;
}
/**
 * 
 * @param text
 * @param key
 * @param style
 * @return
 */
function highlight(text, key, style) {
    try {
        if(key.length == 0) {
            throw new Error('error: keyword field is empty');
        }

        var rc = '';
        
        if(text.toLowerCase().search(key.toLowerCase()) == -1) {
        	return text;
            throw new Error('error: wrong keyword');
        }
        var s = '';
        var links = '';
        
        for(var i = 0; i != text.length - 1; i++) {
            if(text.charAt(i) == '<' && text.charAt(i + 1).toLowerCase() == 'a') {
                for(var j = i; j != text.length - 1; j++) {
                    if(text.charAt(j).toLowerCase() == 'a' && text.charAt(j + 1) == '>') {
                        links += text.charAt(j);
                        links += text.charAt(j + 1);
                        links += '~!~';
                        break;
                    } else {
                        links += text.charAt(j);   
                    }
                }
            }
        }
        
        links = links.split('~!~');
        text = text.replace(/<a[^>]*?>.*?<.a>/gi, "~~~~~"); 

        
        for(var i = 0; i != text.length; i++) {
            if(text.charAt(i).toLowerCase() == key.charAt(0).toLowerCase()) {
                for(var j = 0; j != key.length; j++) {
                    s += text.charAt(i + j);
                }
                if(s.toLowerCase() == key.toLowerCase()) {
                    rc += style.begin + s + style.end;
                } else {
                    rc += s;    
                } 
                i += s.length - 1;   
                s = '';
            } else {
                rc += text.charAt(i);
            }    
        }
        for(var i = 0; i != links.length; i++) {
            rc = rc.replace(/~~~~~/i, links[i]); 
        }
        return rc;
    } catch(e) {
        rc = e.description;
    }
    return rc;
}

var orangeFont = new Object();
orangeFont.begin = '<font style = "color: orange">';
orangeFont.end = '</font>';

function titleSearch(arrayPosition, key) {
	var s = tags[arrayPosition].title.toLowerCase();
	var k = key.toLowerCase();
	if(s.indexOf(k) == -1) {
		return false;
	} else {
		return true;
	}
}
/**
 * @return returns array of tag Ids
 */
function getTagsListByKey( k ) {
	var OUTPUT_LIMIT = 4;
	//log.debug('action - getTagsListByKey: ', '/'+k+'/', 'length: ' + k.length);
	var tl = tags.length;
	var rc = new Array();
	if($.browser.msie) tl--;
	var curr_tag_text = null;
	for(var i = 0; i != tl; i++) {
		curr_tag_text = $(tags[i].full_desciption).text();
		curr_tag_title = tags[i].title;
		if(rc.length >= OUTPUT_LIMIT) break;
		if(curr_tag_title.toLowerCase().indexOf(k.toLowerCase()) != -1) {
			rc.push({arrayPosition: i,
					           key: k.toLowerCase(),
						   keyCase: k,
	                         title: curr_tag_title, 
	                            id: tags[i].id, 
	                    firstIndex: curr_tag_text.toLowerCase().indexOf(k.toLowerCase()),
	                      priority: 1,
	                   description: curr_tag_text.toLowerCase(),
	               descriptionCase: curr_tag_text});
			continue;
		}
		if(curr_tag_text.toLowerCase().indexOf(k.toLowerCase()) != -1) {
			rc.push({arrayPosition: i,
					           key: k.toLowerCase(),
						   keyCase: k,
	                         title: curr_tag_title, 
	                            id: tags[i].id, 
	                    firstIndex: curr_tag_text.toLowerCase().indexOf(k.toLowerCase()),
	                      priority: 0,
	                   description: curr_tag_text.toLowerCase(),
	               descriptionCase: curr_tag_text});	
		}
		
	}
	return rc;
}

function getTagIndexByTitle(title, tagsList) {
	for(var i = 0; i < tagsList.length; i++) {
		if(tagsList[i].title == title) {
			return i;
		}
	}
}

function getLiteString(tag, key) {
	if(tag.description.indexOf(key.toLowerCase()) != -1) {
		var styleStart = '<font style = "color: orange; font-weight: bold">';
		var styleEnd = '</font>';
		var preKey = '';
		var postKey = '';
		var preKeyCounter = 0;
		var postKeyCounter = 0;
		var rc = '';
		var keyCase = '';
		var test = '';
		
		for(var i = 0; i < tag.firstIndex; i++) {
			preKey += tag.descriptionCase.charAt(i);
			if(tag.descriptionCase.charAt(i) == " ") {
				preKeyCounter++;
				if(preKeyCounter == 4) break;
			}	
		}
		
		
		for(var j = tag.firstIndex + key.length; j != tag.descriptionCase.length; j++) {
			test += tag.descriptionCase.charAt(j);
		}
		
		for(var j = 0; j != test.length; j++) {
			postKey += test.charAt(j);
			if(test.charAt(j) == " ") {
				postKeyCounter++;
				if(postKeyCounter == 7) break;
			}
		}
		
		for(var t = tag.firstIndex; t != tag.firstIndex + tag.keyCase.length; t++) {
			keyCase += tag.descriptionCase.charAt(t);
		}
		rc = '...' + preKey + styleStart + keyCase + styleEnd + postKey + '...';
		return rc;	
	}
	rc = 'no maches here';
	return rc;
}
/**
 * 
 * @param tagsList
 * @param key
 * @return void
 */
function setTags(new_tags, key) {
	styleStart = '<font style = "color: orange;">';
	styleEnd = '</font>';
	
	var e = document.getElementById('b_search_list_i');
	
	var titles = new Array();
	var current = null;
	var description = new Array();
	var test = '';

	for(var j = 0; j < new_tags.length; j++) {
		if(new_tags[j].priority == 0) {
			titles.push( new_tags[j].title );
		}
	}

	titles.sort();
	
	for(var j = 0; j < new_tags.length; j++) {
		if(new_tags[j].priority == 1) {
			$('#b_search_list').show();
			e.innerHTML += '<h6 style = "cursor: pointer;" title = "'+ key + '" onclick = "' + "setDescription($(this).text(), this.title)" + '">' + styleStart + new_tags[j].title + styleEnd + '</h6>';
			if(isInDescription(new_tags[j], key) == true) {
				e.innerHTML += '<p>' + getLiteString(new_tags[j], key) + '</p>';
			} else {
				e.innerHTML += '<p>' + '&nbsp;' + '</p>';
			}
		} 
	}
	for(var j = 0; j < titles.length; j++) {
		$('#b_search_list').show();
		e.innerHTML += '<h6 style = "cursor: pointer;" title = "'+ key + '" onclick = "' + "setDescription(this.innerHTML, this.title)" + '">' + titles[j] + '</h6>';
		e.innerHTML += '<p>' + getLiteString(new_tags[getTagIndexByTitle(titles[j], new_tags)], key) + '<p>';
	}
}
function isInDescription(tag, key) {
	if(tag.description.indexOf(key.toLowerCase()) != -1) {
		return true;
	}
	return false;
}
function setDescription(title, key) {
	var tagLen = tags.length;
    if($.browser.msie) {
    	tagLen--; 
    }
	for(var i = 0; i != tagLen; i++) {
		if(title.toLowerCase() == tags[i].title.toLowerCase()) {
			$('#tagTitleClassic').html(tags[i].title);
			$('#tagDescriptionClassic').html(highlight(replaceUmlauts(tags[i].full_desciption), key, orangeFont));
		}
	}
}

function replaceUmlauts(s) {
	var rc = s
	.replace(/&Auml;/g, 'Ä')
	.replace(/&Ouml;/g, 'Ö')
	.replace(/&Uuml;/g, 'Ü')
	.replace(/&auml;/g, 'ä')
	.replace(/&ouml;/g, 'ö')
	.replace(/&uuml;/g, 'ü')
	.replace(/&szlig;/g, 'ß');
	return rc;
}
