// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// name/init_type.js
//
// copyright (c) 2009-2011 drow <drow@bin.sh>
// all rights reserved.

var local_ref=/http:..donjon.bin.sh/i,google_query=/http:..www.google.+[?&]q=([^&]+)/i,bing_query=/http:..www.bing.+[?&]q=([^&]+)/i,msn_query=/http:..search.msn.+[?&]q=([^&]+)/i,yahoo_query=/http:..search.yahoo.+[?&]p=([^&]+)/i,misc_query=/http:..(.+)/i;function init_type(a){a=$(a).elements;var c;if(c=match_type(a)){c.sub_type&&setv(a[c.type],c.sub_type);setv(a.type,c.type);return true}else return false}
function match_type(a){if(hash=window.location.hash)if(match=match_hash(a,hash))return match;if(query=get_query()){var c=query.map(build_regex);if(match=search_types(a,c))return match}return false}function match_hash(a,c){var b=false;$A(a.type.options).each(function(d){if(hash_type(d.value)==c)b={type:d.value};a[d.value]&&$A(a[d.value].options).each(function(e){if(hash_type(e.value)==c)b={type:d.value,sub_type:e.value}})});return b}
function get_query(){var a;if(proto=window.location.search){a=proto.toQueryParams();a=a.type?a.type:proto.substring(1)}else if(proto=window.location.hash)a=proto;else if(proto=document.referrer)if(local_ref.test(proto))return false;else if(match=google_query.exec(proto))a=match[1];else if(match=bing_query.exec(proto))a=match[1];else if(match=msn_query.exec(proto))a=match[1];else if(match=yahoo_query.exec(proto))a=match[1];else if(match=misc_query.exec(proto))a=match[1];if(a)return tokenize(a);return false}
function tokenize(a){a=a.replace(/%\w\w/g," ");a=a.replace(/\W+/g," ");a=a.replace(/_+/g," ");a=a.replace(/\s+/g," ");a=a.replace(/^ /,"");a=a.replace(/ $/,"");return a.split(" ").uniq().without("name","generator")}function build_regex(a){return{word:a,full:new RegExp("\\b"+a+"\\b","i"),head:new RegExp("\\b"+a,"i"),tail:new RegExp(a+"\\b","i"),misc:new RegExp(a,"i")}}
function search_types(a,c){var b={};$A(a.type.options).each(function(e){var f=opt_text(e);if(score=score_opt(f,c))b[e.value]=score;a[e.value]&&$A(a[e.value].options).each(function(g){var h=f+" "+opt_text(g);if(score=score_opt(h,c))b[e.value+"|"+g.value]=score})});var d;if(d=high_score(b)){b=d.split("|");return{type:b[0],sub_type:b[1]}}return false}function opt_text(a){return a.value+" "+a.text}
function score_opt(a,c){var b=0;tokenize(a).each(function(d){c.each(function(e){if(d.match(e.full))b+=1;else if(d.match(e.head))b+=0.9;else if(d.match(e.tail))b+=0.8;else if(d.match(e.misc))b+=0.7})});return b}function high_score(a){var c=0,b=false;$H(a).each(function(d){if(d.value>c){b=d.key;c=d.value}});return b}function herald_type(a){if(!window.location.search)window.location.hash=hash_type(a)}function hash_type(a){return"#"+a.toLowerCase().replace(/\W+/g,"_")};

