
function adServer () {
  
    this.ads  		= {10: {'id':[10], 'url':['http://www.gopstore.com'], 'category':['donations','store'],'sizes': ['837x364','407x242','266x242'], 'weight':1, 'keywords':['store','gop','rnc','buy','collectibles']}, 17: {'id':[17], 'url':['http://volunteer.gop.com/volunteer-from-home'], 'category':['volunteer'],'sizes': ['837x364','407x242','266x242'], 'weight':1, 'keywords':['volunteer']}, 20: {'id':[20], 'url':['http://volunteer.gop.com'], 'category':[''],'sizes': ['837x364','407x242','266x242'], 'weight':1, 'keywords':['volunteer']}, 30: {'id':[30], 'url':['http://www.gop.com/index.php/issues/future_leaders'], 'category':[''],'sizes': ['837x364','407x242','266x242'], 'weight':1, 'keywords':['']}, 31: {'id':[31], 'url':['http://www.youtube.com/rnc#p/a/u/0/7LgzOCHcRMQ'], 'category':[''],'sizes': ['407x242'], 'weight':1, 'keywords':['']}, 22: {'id':[22], 'url':['https://donate.gop.com'], 'category':['volunteer'],'sizes': ['837x364','407x242','266x242'], 'weight':1, 'keywords':['volunteer']}};
    this.keywords   = buildKeywordString();
    this.categories = new Array();

	//weight ads
	for(id in this.ads) {
		if(this.ads[id].url == window.location.href) {
			delete this.ads[id]; //remove ad
		} else {
			ai = array_intersect(this.keywords, this.ads[id].keywords);
			this.ads[id].weight = parseInt(this.ads[id].weight) + ai.length;
        }
    }
    this.displayAd = function(w, h, cat, zip) {
    
    	w   = isInt(w) ? parseInt(w) : 0;
    	h   = isInt(h) ? parseInt(h) : 0;
        zip = parseInt(zip);
        cat = escape(cat);
        
        ads_avail = {};
        for(id in this.ads) {
        	if(in_array(w+"x"+h, this.ads[id].sizes)) {
            	ads_avail[id] = this.ads[id].weight;
            } 
        }
		
        cat_ads = {};   
             
        if(cat !== undefined && cat !== null && cat !== '') {
            for(i in ads_avail) {
            	if(in_array(cat, this.ads[i].category)) 
            		cat_ads[i] = ads_avail[i];
           	}
		}
 		//alert(print_r(ads_avail, true));
        if(!isEmpty(cat_ads)) {
            ad_id = chooseRandom(this.weightArray(cat_ads));
        } else {
			ad_id = chooseRandom(this.weightArray(ads_avail));
        }    
        loc 	= escape(window.location.href);
        display = "";
        
        if(ad_id != -1) {

            //if(type == 'victoryoffice') {
			//	document.write("<scr"+"ipt type=\"text/javascript\" src=\"http://maps.google.com/maps/api/js?sensor=false\"></scr"+"ipt>");
			//}
            display = "<scr"+"ipt type=\"text/javascript\" src=\"http://gop.com/gop_delivery_network/?id="+ad_id+"&size="+w+"x"+h+"&loc="+loc+"&zip="+zip+"&var1=&var2=&var3=\"></scr" + "ipt>";
			delete this.ads[ad_id];
         }
         document.write(display);
    }
    
    this.weightArray = function(a) {
    	
    	res_weights = {};
        
        f1  = '';
        num = 0;
        for(i in a) {
        	f1 = i;
        	num++;
        }
        if(num == 1) {
            res_weights[f1] = 100;
        } else {
            total_weight  = parseInt(sumArray(a));
            cur_res_total = 0;
            
            for(id in a) {
            	if(parseInt(a[id])) {
                	cur_res_total  += (parseInt(a[id]) / total_weight) * 100;
                	res_weights[id] = cur_res_total;
                }
            }
        }
        return res_weights;
    }
}

function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
} 
    
function sumArray(a) {
    total = 0;
    for(id in a) {
        total += a[id];
    }
    return total;
}

function chooseRandom(wa) {
	rnum = Math.floor(Math.random() * 101);
    for(key in wa) {
		if(rnum <= wa[key]) {
			return key;
		}
	}
    return -1;
}
function isEmpty(obj) {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
}
function in_array (needle, haystack) {
    var key = '';
    for (key in haystack) {
        if (haystack[key].toUpperCase() == needle.toUpperCase()) {
            return true;
        }
    }
    return false;
}

function buildKeywordString () {

	var metas	  	  = ['title', 'keywords', 'tags', 'description'];
	var res_array 	  = new Array();
    var k_index   	  = 0;
    var post_keywords = "";
    var post_tags 	  = "";
    
    for(i in metas) {
    	meta = metas[i];
    	if(meta == 'title') {
        	//do work
        } else if(meta == 'description') {
        	//do work
        } else if(meta == 'keywords' || meta == 'tags') {
    		var mstr = getmetaContents(meta);
            mstr 	 = mstr.toLowerCase();
            var keys = mstr.split(",");
            for(j in keys) {
            	var trim_key = trim(keys[j]).replace("'", "\\'");
                if(!in_array(trim_key, res_array)) {
                    res_array[k_index] = trim_key;
                    eval('post_'+meta+' += \''+trim_key+',\'');
                    k_index++;
                }
            }
		} else {
        	//do work
        }      
    }
    if(getmetaContents('title') == '') {
    	var title = document.title;
    } else {
   		var title = getmetaContents('title');
    }
    
    //$.get("http://gop.com/gop_delivery_network/log_page.php", {'keywords': getmetaContents('keywords') + ',' + getmetaContents('tags')}, function(data){alert(data.state}, "json");

    return res_array;
}

function getmetaContents (mn){ 
	var m = document.getElementsByTagName('meta'); 
	for(var i in m){ 
		if(m[i].name == mn){ 
			return m[i].content; 
		} 
	}
    return '';
}

function trim (str) {
    str += '';
    whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
        	str = str.substring(i);
            break;
        }
    }
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function array_intersect () {
    var arr1 = arguments[0], retArr = new Array();
    var k1 = '', arr = {}, i = 0, k = '';    
    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i=1; i < arguments.length; i++) {            
        	arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1]) {
                    if (i === arguments.length-1) {
                        retArr.push(arr1[k1]);
                    }
                }
            }
            continue arr1keys;
        }
    }
     return retArr;
}

function print_r (array, return_val) {    
    var output = "", pad_char = " ", pad_val = 4, d = this.window.document;    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }        return name[1];
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";        for (var i=0; i < len; i++) {
            str += pad_char;
        }
        return str;
    }; 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        } 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
         if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !== 'PHPJS_Resource') {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";        } else if (obj === null || obj === undefined) {
            str = '';
        } else { // for our "resource" class
            str = obj.toString();
        } 
        return str;
    };
 
    output = formatArray(array, 0, pad_val, pad_char); 
    if (return_val !== true) {
        if (d.body) {
            this.echo(output);
        }        else {
            try {
                d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
                this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">'+output+'</pre>');
            }            catch (e) {
                this.echo(output); // Outputting as plain text may work in some plain XML
            }
        }
        return true;    } else {
        return output;
    }
}

var vf_fontSize     = 1.6;
var vf_unit         = 'em';
var vf_increment    = .1;
var vf_tolerance    = 0;
var vf_trigger      = 'verticalFill';

//DO NOT CHANGE ANYTHING BELOW THIS LINE!
//==================================================================================

function vf(el, finalheight, curSize){
  if(el.innerHTML == '') return;
  var currentheight = el.offsetHeight;
  var fontsize      = curSize; 
  
  if(currentheight > finalheight)
  {
    fontsize -= vf_increment;
    el.style.fontSize = fontsize+vf_unit;
    vf_last = '-';
    vf(el, finalheight, fontsize);
  }
  else if(currentheight < finalheight && vf_last!='-')
  {
    fontsize += vf_increment;
    el.style.fontSize = fontsize+vf_unit;
    vf_last = '+';
    vf(el, finalheight, fontsize);
  }
  else
  {
      vf_last = '';
      return null;
  }
}

function vf_getElementsByClassName(className, tag, el){
  var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
  var tag = tag || "*";
  var el = el || document;
  var elements = (tag == "*" && el.all)? el.all : el.getElementsByTagName(tag);
  var returnElements = [];
  var current;
  var length = elements.length;
  for(var i=0; i<length; i++){
      current = elements[i];
      if(testClass.test(current.className)){
          returnElements.push(current);
      }
  }
  return returnElements;
}

function vf_init()
{
  var vf_elements = vf_getElementsByClassName(vf_trigger);
  vf_last = '';
  for(i=0;i<vf_elements.length;i++)
  {
      el=vf_elements[i];
      if(el.currentStyle){
        var pt = el.parentNode.currentStyle['paddingTop'];
        var pb = el.parentNode.currentStyle['paddingBottom'];
        var mt = el.currentStyle['marginTop'];
        var mb = el.currentStyle['marginBottom'];
      }else if(window.getComputedStyle || document.defaultView.getComputedStyle){
        var pt = document.defaultView.getComputedStyle(el.parentNode,null).getPropertyValue('padding-top');
        var pb = document.defaultView.getComputedStyle(el.parentNode,null).getPropertyValue('padding-bottom');
        var mt = document.defaultView.getComputedStyle(el,null).getPropertyValue('margin-top');
        var mb = document.defaultView.getComputedStyle(el,null).getPropertyValue('margin-bottom');
      }else{
        var pt = 0;
        var pb = 0;
        var mt = 0;
        var mb = 0;
      }
      var finalHeight = el.parentNode.offsetHeight - ( parseFloat(pt) + parseFloat(pb) + parseFloat(mt) + parseFloat(mb) + parseFloat(vf_tolerance) );
      el.style.fontSize = vf_fontSize+vf_unit;
      vf(el, finalHeight, vf_fontSize);
  }
}

window.onload = vf_init;

//document.write("<scr"+"ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js\"></scr" + "ipt>");
document.write("<scr"+"ipt language=\"JavaScript\" type=\"text/javascript\">var ads = new adServer();</scr"+"ipt>");