// JavaScript Document

var abVar;
var abPrevGen;

var britepic_id;
var britepic_src;
var britepic_width;
var britepic_height;
var britepic_show_ads;
var britepic_show_menu;
var britepic_keywords;
var britepic_caption;
var britepic_href;
var britepic_target;

if (abPrevGen != true)
{
	abStartBritePic();
}


function abStartBritePic ()
{	
	if (abVar == undefined)
	{
		abVar = new Object();
		abVar.viewerPath = 'http://www.britepic.com/britepic';
		abVar.swfList = new Array();
		abVar.divList = new Array();
		abVar.picDataList = new Array();

		// Define a class to store each BritePic's data until onLoad event fires
		abVar.PicDataObj = function (aID, aSrc, aW, aH, aShow_ads, aShow_menu, aKeywords, aCaption, aHref, aTarget) {
			this.id = aID;
			this.src = aSrc;
			this.width = aW;
			this.height = aH;
			this.show_ads = aShow_ads;
			this.show_menu = aShow_menu;
			this.keywords = aKeywords;
			this.caption = aCaption;
			this.href = aHref;
                        this.target = aTarget;	
		}
		
		abVar.bpNum = 0;
		
		if (abPrevGen != true)
		{
			// Add our onLoad function while preserving anything the publisher already had assigned to window.onLoad;
			abVar.oldonload = window.onload;
			
			if (typeof window.onload != 'function') {
				window.onload = abWriteAllPics;
			}
			else {
				window.onload = function() {
					abVar.oldonload();
					abWriteAllPics();
				}
			}
		}
		
		// Determine if this is IE on Windows - if so, we can't write all BPs at once onLoad. We must use setInterval to increment through the list.
		abVar.isIE = abCheckForWinIE();
	}
	
	// Check if a caption has been set to anything, or to "", or not set at all
	abCheckForEmptyCap();
	
	abCheckForShowAds();
	
	abCheckForShowMenu();
	
	var tempPicData = abGetPicData();
	
	abCreateBritePic(tempPicData);
	
	abResetAllPicProps();	// Delete all publisher-set props so that settings from this BPic instance don't get carried down to the next BPic on the page.
}


// ============================== Functions for compiling the data from user's JavaScript settings ============================== //


function abCheckForEmptyCap ()
{
	try
	{
		britepic_caption === undefined || britepic_caption === null;
	}
	catch (e)
	{
		britepic_caption = 0;
	}
	finally
	{
		if (britepic_caption === "")
		{
			britepic_caption = "abNull";	// If the user explicitly set a caption of "", pass in a keyword that the viewer knows means [empty]
		}
	}
}


function abCheckForShowAds ()
{
	try
	{
		if(britepic_show_ads === undefined || britepic_show_ads === null)
		{
			britepic_show_ads = "abNull";
		};
	}
	catch (e)
	{
//		alert ("abNull");
		britepic_show_ads = "abNull";
	}
}


function abCheckForShowMenu ()
{
	try
	{
		if(britepic_show_menu === undefined || britepic_show_menu === null)
		{
			britepic_show_menu = "abNull";
		};
	}
	catch (e)
	{
//		alert ("abNull");
		britepic_show_menu = "abNull";
	}
}


function abGetPicData ()
{
	var tID = abGetPropVal("id");
	var tSrc = abGetPropVal("src");
	var tW = Math.round(abGetPropVal("width"));
	var tH = Math.round(abGetPropVal("height"));
	var tShow_ads = abGetPropVal("show_ads");
	var tShow_menu = abGetPropVal("show_menu");
	var tKeywords = abGetPropVal("keywords");
	var tCaption = abGetPropVal("caption");
	var tHref = abGetPropVal("href");
	var tTarget = abGetPropVal("target");
	
	// If width or height aren't set properly, set them to 0 (false)
	if (typeof(tW) != "number" || tW < 1)
	{
		tW = 0;
	}
	if (typeof(tH) != "number" || tH < 1)
	{
		tH = 0;
	}
	/*
	if (typeof(tShow_ads) != "number" || tShow_ads != 0)
		 tShow_ads = 1;
	}
	*/
	// Clean up the keywords
	if (tKeywords != 0)
	{
		tKeywords = abCleanKeywords(tKeywords);
	}
	
	// Clean up the caption
	if (tCaption != "abNull")
	{
		tCaption = abCleanCap(tCaption, tSrc);
	}
	
	return new abVar.PicDataObj (tID, tSrc, tW, tH, tShow_ads, tShow_menu, tKeywords, tCaption, tHref, tTarget);
}


function abGetPropVal (aPropID)
{
	var curProp = this["britepic_" + aPropID];
	var curVal;
	curProp != undefined && curProp != 0 ? curVal = curProp : curVal = 0;
        return curVal;
}


function abCleanKeywords (aKeywords)
{
	// NO time to do reg-exp matching for now, so just make sure the keywords string isn't longer than 500 chars
	if (aKeywords.length > 500)
	{
		aKeywords = aKeywords.slice(0, 500);	
	}
	
	// Make sure no characters are in the keywords that will screw up the var string
	return escape(aKeywords);
}


function abCleanCap (aCap, aSrc)
{
	// If a caption was not set, create one from the file name
	if (aCap == 0)
	{
		aCap = abGetCapFromSrc(aSrc);
	}
	
	// NO time to do reg-exp matching for now, so just make sure the caption string isn't longer than 150 chars
	if (aCap.length > 150)
	{
		aCap = aCap.slice(0, 150);
	}
	
	// Make sure no characters are in the caption that will screw up the var string
	return escape(aCap);
}


function abGetCapFromSrc (aSrc)
{
	// Use the file name (after the last / in the URL)
	var l = aSrc.length;
	var s = aSrc.lastIndexOf("/");
	var tc = aSrc.slice(s + 1);
	
	// Remove file extension if there is one
	var d = tc.lastIndexOf("."); 
	if (d > 0)
	{
		tc = tc.slice(0, d);	
	}
	
	// Replace underscores with spaces
	if (tc.indexOf("_") > 0)
	{
		tc = tc.split("_");
		tc = tc.join(" ");
	}
	return tc;
}


// ============================== Functions that happen BEFORE onLoad ============================== //




function abCreateBritePic (aPicData)
{
	// Create ID strings for the SWF Object/Embed tags, and for the containing DIV
	abVar.bpNum += 1;
	var divID = "abBP_" + abVar.bpNum;
	var objID = divID + '_Obj'; 
		
//	alert("needSizes: " + aPicData.needSizes + " --- W: " + aPicData.width);
	// Build the var string to pass into the swf on the object/embed flashvars string
	var varString = "js=1&divID=" + divID + "&href=" + aPicData.href + "&target=" + aPicData.target;	// NOT passed back from SWF to back-end
        varString += '&id=' + aPicData.id + '&src=' + aPicData.src + "&width=" + aPicData.width + "&height=" + aPicData.height + '&show_ads=' + aPicData.show_ads + '&show_menu=' + aPicData.show_menu + '&keywords=' + aPicData.keywords + '&caption=' + aPicData.caption;
	
	// Write the placeholder div to attach the swf object to onLoad
	var divCode_swf = AB_GetDivString(divID);
	document.write(divCode_swf);
	
	var divID_img = divID + "_img";
	var divCode_img = AB_GetDivString_img(divID_img, aPicData);
	document.write(divCode_img);
	
	// Add the div to an array so it can be accessed quickly at onLoad
	var curDiv = abGetDomObj(divID);
	abVar.divList.push(curDiv);
	
	// Write the object/embed code and store it so it can be written quickly at onLoad
	var swfCode = AB_GetObjEmbedString('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0','width','100%','height','100%','id',objID,'align','middle','src',abVar.viewerPath,'FlashVars',varString,'quality','best','bgcolor','#ffffff','name',objID,'allowscriptaccess','always','pluginspage','http://www.macromedia.com/go/getflashplayer','movie',abVar.viewerPath,'wmode','transparent'); //end AC code
	abVar.swfList.push(swfCode);
	
	// Store this instance's picData so the sizes can be accessed again at onLoad
	abVar.picDataList.push(aPicData);
}


function abResetAllPicProps ()
{
	britepic_id = britepic_src = britepic_width = britepic_height = britepic_keywords = /*britepic_caption =*/ britepic_href = britepic_target = 0;
//	delete britepic_caption;
	britepic_show_ads = britepic_show_menu = britepic_caption = null;
	return;
}


function abCheckForWinIE ()
{
	abVar.userAgent = navigator.userAgent; 
	abVar.isOpera = abVar.userAgent.indexOf('Opera') > -1; 
	return abVar.userAgent.indexOf('compatible') > -1 && abVar.userAgent.indexOf('MSIE') > -1 && !abVar.isOpera;
}



// ============================== Functions that happen AFTER onLoad ============================== //



function abWriteAllPics ()
{
	abVar.picTotal = abVar.swfList.length;
		
	if (abVar.isIE)
	{	
		abVar.curPic = 0;
		abNextPicInt();
		abVar.picInt = setInterval("abNextPicInt()", 200);
	}
	else
	{	
		for (i=0; i<abVar.picTotal; i++)
		{
			abWriteSwfToDiv(i);
		}	
	}
}


function abNextPicInt ()
{
	abVar.curPic += 1;
	
	if (abVar.curPic <= abVar.picTotal)
	{
		var i = abVar.curPic - 1;

		abWriteSwfToDiv(i);
	}
	else
	{
		clearInterval(abVar.picInt);	
	}
}


function abWriteSwfToDiv (i)
{
//	alert ("abWriteSwfToDiv: " + i);
	
	var curDiv = abVar.divList[i];
	var curSwf = abVar.swfList[i];
	var curPicData = abVar.picDataList[i];
	
	curDiv.innerHTML = curSwf;
}


function abSetDivSize (aDivID, aW, aH)
{
//	alert ("abSetDivSize: " + aDivID + " --> " + aW + "/" + aH);
	
	var bp = abGetDomObj(aDivID);
	
	aW += "px";
	aH += "px";
	
	abSetStyleProp(aDivID, "width", aW);
	abSetStyleProp(aDivID, "height", aH);
	abSetStyleProp(aDivID, "display", "block");
	abSetStyleProp(aDivID, "visibility", "visible");
	
	var imgDiv = aDivID + "_img";
	abSetStyleProp(imgDiv, "display", "none");
}


function abSetStyleProp (aObjID, aPropID, aValue)
{
	var obj = abGetDomObj(aObjID);
	obj.style[aPropID] = aValue;
}


function abGetDomObj (aElementID)
{
	return document.getElementById(aElementID);
}


// ===================== The following methods are all imported from Adobe's Active Content scripts out of Flash and modified for BritePic ===================== //

//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.


function AB_GetDivString(aDivID)
{
	 return '<div class="abBritePic" id="' + aDivID + '" name="' + aDivID + '" style="width:120px; height:20px;"></div>'	
}


function AB_GetDivString_img(aDivID, aPicData)
{
	// Compost an IMG tag
	var imgStr = '<img class="abTempImg" src="' + aPicData.src + '"';
	if (aPicData.width > 0) {
		imgStr += ' width="' + aPicData.width + '"';
	}
	if (aPicData.height > 0) {
		imgStr += ' height="' + (aPicData.height - 20) + '"';
	}
	
	var styleStr = ' style="border-style:none; border-width:0px; border-color:transparent; outline-style:none; outline-width:0px; margin:0px; padding:0px; background-color:transparent;" ';
	
	imgStr += (styleStr + '>');
	
	var divStr = '<div class="abBritePic_img" id="' + aDivID + '" name = "' + aDivID + '">' + imgStr + '</div>';

//	alert ("Image Div: " + divStr);
	 return divStr;
}


function AB_GetObjEmbedString(){
 	var ret = 
    AB_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
        return swfCode = AB_GenerateString(ret.objAttrs, ret.params, ret.embedAttrs);
}


function AB_GenerateString(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  return str;
}


function AB_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
		ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
		break;
      case "wmode":		// Added for AdBrite BritePic Only
		default:
		ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}
