//////////////////////////////////////////////////////////
/// Script Purprose: Generate Helios IQ ad tags - Emmis
/// Version: 0.1
/// Created By: Dimitry Chertkov(2009)
/// Uploaded: 06212010
//////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////
/// SET DEFAULT VARIABLES FOR GENERIC STATION SETTINGS
//////////////////////////////////////////////////////////
var DEFAULT_SITE_NAME     = "default";
var DEFAULT_AD_SIZE		  = "1x1";
var DEFAULT_ZONE          = "other";
var DEFAULT_HOMEPAGEZONE  = "home";   
var DEFAULT_LANDING_ZONE  = "landing";

//////////////////////////////////////////////////////////
// Cross-browser JavaScript support fuctions
//////////////////////////////////////////////////////////

//indexOf() function not supported by IE
if(!Array.indexOf)
{
    Array.prototype.indexOf = function(obj, start)
    {
        for(var i=(start||0); i <this.length; i++)
        {
            if(this[i]==obj)
            {
                return i;
            }
        }
        return -1;
    }
}

//getElementById function is not supported by all browsers
function getElement(id){
    if(document.getElementById)
    {
        getElement = function(id){return document.getElementById(id).innerHTML;};
    }
    else if(document.all)
    {
        getElement =  function(id){return document.all[id].innerHTML;};
    }
    else if(document.layers)
    {
        getElement =  function(id){return document.layers[id].innerHTML;};
    }
    else
    {
        getElement = function(){return null;};
    }
    
    return getElement(id);          //getElement function has been replaced with a browser appropriate version
}

//////////////////////////////////////////////////////////
/// Ad Object
//////////////////////////////////////////////////////////

function Ad(site, aliasZone, keys) 
{
    this.site = (site)?site:DEFAULT_SITE_NAME;                              //site Attribute
    
    this.aliasZone = (aliasZone)?aliasZone:Ad.convertPathToZoneName();      //aliasZone Attribute

    if(keys)Ad.Keys = new Keys(keys,DEFAULT_AD_SIZE);                       //keys
    
	//page root path to be sent as key word parameter - capped at 60 characters   
    this.rootPath = (document.location.hostname != "undefined"  && document.location.hostname != "")?(document.location.pathname.toLowerCase()+document.location.search.toLowerCase()).substr(0,60):""; 
    
	//page root path to be sent as key word parameter without parameters - capped at 60 characters   
    this.rootPathNP = (document.location.hostname != "undefined"  && document.location.hostname != "")?(document.location.pathname.toLowerCase()).substr(0,60).substr(0,document.location.pathname.indexOf(".aspx")+5):""; 
	   
    this.adGroupId = Ad.getAdGroupID();                                     //groupID - used to goup all tags on the same page together 
    
    this.offset = Ad.getTimeZoneOffset();                                   //Timezone Offset
    
    this.write = write;                                                     //write ad tag method   
    
}
//////////////////////////////////////////////////////////
/// Ad Vars
//////////////////////////////////////////////////////////

//Site homepage url identifiers
Ad.homeID = ['/','','/index.aspx'];

//Site landing page url identifiers
Ad.landingID = ['/landing','/landingpage','/childrensfund.aspx','/Music/Index.aspx','/Concerts/Index.aspx','/FunStuff/Index.aspx','/Hosts/Index.aspx','/Contests/Index.aspx','/Sports.aspx','/Sports/Stamps/Home.aspx','/Weather/Edmonton/Index.aspx','/PhotoGallery/PhotoGallery.aspx','/insideedge/','/HomeOfTheLeafs/'];

//Backup Ad IDs
Ad.BackUpId = {
    "1x1"       : "1203131",
    "1x2"       : "1203130",
    "100x100"   : "1203129",
    "120x90"    : "1203123",
    "130x50"    : "1203132",
    "150x90"    : "1203128",
    "160x600"   : "1203127",
    "170x76"    : "1203126",
    "180x150"   : "1203141",
    "180x180"   : "1203137",
    "200x100"   : "1203139",
    "240x100"   : "1203142",
    "240x90"    : "1203136",
    "25x25"     : "1203124",
    "300x250"   : "1203135",
    "300x40"    : "1203133",
	"320x50" 	: "1203138",
    "500x500"   : "1203143",
    "545x90"    : "1203147",
    "592x90"    : "1203146",
    "728x90"    : "1203148",
    "950x100"   : "1203145",
    "950x150"   : "1203144"
}

//////////////////////////////////////////////////////////
/// Ad Functions
//////////////////////////////////////////////////////////

Ad.convertPathToZoneName = function() 
{
    var ads_zone_name = DEFAULT_ZONE;

    if(document.location.hostname != "undefined"  && document.location.hostname != "")
    {
        var root_path = document.location.pathname.toLowerCase(); 

        (Ad.homeID.indexOf(root_path)>-1)?ads_zone_name = DEFAULT_HOMEPAGEZONE:ads_zone_name = DEFAULT_ZONE ; //check if homepage

    }
    
    return ads_zone_name;    
}

Ad.getTimeZoneOffset = function()
{
    var curDateTime = new Date(); 
    var offset = -(curDateTime.getTimezoneOffset()); 
    offset = (offset>0)?"+" + offset:offset;
    return offset;
}

Ad.getAdGroupID = function()
{
    return Math.round(Math.random()*1000000);
}


//write adtag
function write(adSize,aliasZone,keys,keywords,kwlp)
{     
        //build ad alias
        var alias = this.site+"_";
	    //alias += (aliasZone)?aliasZone + "_":this.aliasZone + "_";  //add alias zone
	    
        if(aliasZone)                                               //zone manually added to ad tag
        {
            alias += aliasZone + "_";
        }
        else if (this.aliasZone != DEFAULT_ZONE)                    //zone already defined as homepage,landing or subsection
        {
            alias += this.aliasZone + "_";
        }
        else                                                        //define zone as landing or subsection
        {
            //check for subsection
            var tempAlias = "";
            try
	        {
	            tempAlias += getElement('sectionID');
	        }
	        catch(err)
	        {
	            tempAlias += DEFAULT_ZONE;
	        }
	        
            var root_path = document.location.pathname.toLowerCase().substring(0,document.location.pathname.lastIndexOf('/'));                                        
            
            //Check for landing
            for(var n=0; n<Ad.landingID.length; n++)
            {
                if(root_path.search(Ad.landingID[n])>-1)
                {
                    tempAlias += DEFAULT_LANDING_ZONE;
                    break;                                      //break out of loop if subsection ID found 
                }           
            }

            this.aliasZone = tempAlias;
            alias += tempAlias + "_";
        }
        
	    alias += (adSize)?adSize:DEFAULT_AD_SIZE;       //add alias adSize
	    
	    //add ad instance to Ad.adTags
	    var newAd = new Ad(this.site,alias);
	    var adTagIndex = Ad.SetInstance(newAd);
	    //set instance size
	    newAd.adSize = (adSize)?adSize:DEFAULT_AD_SIZE;
	    //set instance alias
	    newAd.alias = alias;
	    //set instance keys
	    if(keys)Ad.setKeys(adTagIndex,keys);
      
       
	    document.write('<scr'+'ipt language="javascript1.1" src="http://adserver.adtechus.com/addyn/3.0/5233.1/' + Ad.BackUpId[adSize] + '/0/-1/ADTECH;alias=' + alias + ';size=' + adSize + ';' + "key=" + this.rootPath + "+" + this.rootPathNP + eval('(this.Keys)?this.Keys.print()+";":";"') + 'cookie=info;loc=100;target=_blank;grp=' + this.adGroupId + ';misc='+new Date().getTime()+';aduho='+this.offset+';"></scri'+'pt>');
}

//Add and instance of the Ad Object to the adTags array
Ad.SetInstance = function( adTag )
{
	if( ! Ad.adTags )
	{
		Ad.adTags = new Array();
	}
	
	Ad.adTags.push( adTag );
	
	return Ad.adTags.length - 1;
}

Ad.setKeys = function(i,keys)
{
    if(Ad.adTags[i].Keys)
	{
	    Ad.adTags[i].Keys.addKeys(keys);
	}
	else
	{
	    Ad.adTags[i].Keys = new Keys(keys); 
	}    
}
///////////////////////////////////////////////////////////////
/// Keys Object - keys param must be formatted "key+key+key+key"
///////////////////////////////////////////////////////////////
function Keys(keys)
{ 
    
    //local variables
    var maxLength = 8;      //max number of keys
    var newKeys = keys.split("+"); //temp keys array
    
    //create array of key objects
    this.key = new Array(); 
    for(i=0;i<newKeys.length;i++)
    {
        this.key[i]= new Key((this.key.length+1),newKeys[i]); 
    }
    
    //function - returns a Helios formatted list of keys. Up to 'maxLength' keys long 
    this.print = function()
    {
        var tagKeys = "+";
		var keysFound = 0;
		//find tag specific keys
        for(i=0;i<this.key.length && i<maxLength;i++)
        {
            tagKeys += this.key[i].value;
            tagKeys += (i<this.key.length-1)?"+":"";
			keysFound += 1;
		}
		//if there are generic keys available then add them to the tagKeys string
		if(keysFound<maxLength && Ad.Keys.key.length > 0)
		{
				var keySpotsRemaining = maxLength-keysFound;
				var numGenericKeys = Ad.Keys.key.length;
				var numGenericKeysToAdd = (keySpotsRemaining>numGenericKeys)?numGenericKeys:(numGenericKeys-keySpotsRemaining);
				
				for(i=0;i<numGenericKeysToAdd;i++)
				{
					tagKeys += Ad.Keys.key[i].value;
					tagKeys += (i<numGenericKeysToAdd-1)?"+":"";
				}
		}
		
        return tagKeys;
    }
    
    //function - add new keys
    this.addKeys = function(keys)
    {
        var newKeys = keys.split("+");
        for(i=0;i<newKeys.length;i++)
        {
            this.key.unshift(new Key((this.key.length+1),newKeys[i]));
        }     
    }

}

//////////////////////////////////////////////////////////
/// Key Object
//////////////////////////////////////////////////////////
function Key(num,value)
{
   this.num = num;
   this.value = value;
}