var field_to_modify = null;
var input_field_color = null;
var display_color_picker = false;
var display_color_picker_timer = '';
var current_ad = 'IAB-1';
var old_value = null;
var ignore_timer = false;

function show_palette( field ) {
   field_to_modify = field;

   var html_tag = document.getElementById( "colorsample-" + field );
   var x_value = find_x_position( html_tag ) + 20;

   input_field_color = document.getElementById( "colorfield-" + field ).value;

   if ( x_value < 0 ) { x_value=0; } 
   else if ( x_value + 290 > width_of_page() ) { x_value=document.body.offsetWidth - 310; }

   var color_picker_span = document.getElementById("color_picker");
   color_picker_span.style.top = find_y_position(html_tag)+'px';
   color_picker_span.style.left = x_value+'px';
   color_picker_span.style.display = "block";

}

function width_of_page() {
   var width;
   if (self.innerWidth) width = self.innerWidth;
   else if (document.documentElement.clientWidth && document.documentElement.clientWidth) width = document.documentElement.clientWidth;
   else if (document.body.clientWidth) width = document.body.clientWidth;
   return width;
}

function find_x_position(obj) {
   var curleft = 0;
   if (obj.offsetParent) {
      while (obj.offsetParent) {
         curleft += obj.offsetLeft;
         obj = obj.offsetParent;
      }
   } else if (obj.x) curleft += obj.x;
   return curleft;
}

function find_y_position(obj) {
   var curtop = 0;
   if (obj.offsetParent) {
      while (obj.offsetParent) {
         curtop += obj.offsetTop;
         obj = obj.offsetParent;
      }
   } else if (obj.y) curtop += obj.y;
   return curtop;
}

function hidePalette_timer() {
   if (ignore_timer == false) {
      if (display_color_picker != true && field_to_modify != null) {
         set_color(field_to_modify, input_field_color);
         showPreview(current_ad,field_to_modify,input_field_color);
         display_color_picker = false;
         field_to_modify = null;
         document.getElementById( "color_picker" ).style.display = "none";
      }
   } else ignore_timer = false;
}

function hidePalette() {
   display_color_picker = false;
   field_to_modify = null;
   document.getElementById( "color_picker" ).style.display = "none";
}

function rollOverColor(color) {
   window.clearTimeout(display_color_picker_timer);
   showPreview(current_ad,field_to_modify,color);
   //update input/color box
   document.getElementById('colorsample-' + field_to_modify).style.background = '#'+color;
   document.getElementById('colorfield-' + field_to_modify).value = color;
if( field_to_modify == 'url' ) { 
    document.getElementById('butt1').style.borderColor='#'+color; 
	document.getElementById('butt1').style.backgroundColor ='#'+color; 
	document.getElementById('butt2').style.backgroundColor ='#'+color; 
    document.getElementById('butt2').style.borderColor ='#'+color; 
	}

}

function rollOut() {
   display_color_picker_timer = window.setTimeout("hidePalette_timer()", 1000);
}

function on_click_color(color) {
   ignore_timer = true;
   display_color_picker = true;
   
   if( field_to_modify != null ) {
      set_color( field_to_modify, color);
      document.getElementById( "colorfield-" + field_to_modify ).focus();
   }
   hidePalette()
}

function set_color(field,color) {
   field_to_modify=field;
   color=testHex(color);
   if (color != '') { 
      document.getElementById("colorsample-"+field).style.backgroundColor=color; 
      document.getElementById("colorfield-"+field).value=color.slice(1,color.length);
   }
}

function check_color_and_show_preview(value, field) {
   if( testHex(value) != '' ) {
      set_color(field,value);
      showPreview(current_ad,field_to_modify,value);
   }
}

function focused(value, field) {
   old_value=value;
}

function blurred(value, field) {
   if(testHex(value)=='') {
      value=old_value;        
   }

   set_color(field,value);
   showPreview(current_ad,field_to_modify,value);
}

function _refreshField() {
   selected=document.getElementById('ad-size-picker').options[document.getElementById('ad-size-picker').options.selectedIndex].value;
   swap(selected);
   for (var i=0; i<_refreshField.arguments.length; i++) {
      oldColor = document.getElementById('colorfield-'+_refreshField.arguments[i]).value;
      sample = document.getElementById('colorsample-'+_refreshField.arguments[i]);
      oldColor=testHex(oldColor);
      if(oldColor=='') {
         sample.style.backgroundImage = 'url(images/no-color.gif)';
         sample.style.backgroundPosition = 'center center';
         sample.style.backgroundColor='transparent';
      } else {
         sample.style.backgroundImage = '';
         sample.style.backgroundColor = oldColor;
      }
   }
}

function insertHidden() {
   document.getElementById('hidden-title').value = document.getElementById('colorfield-title').value;
   document.getElementById('hidden-background').value = document.getElementById('colorfield-background').value;
   document.getElementById('hidden-text').value = document.getElementById('colorfield-text').value;
   document.getElementById('hidden-border').value = document.getElementById('colorfield-border').value;
}

function updateLayout() {
   var adDir = (document.getElementById('text_layout_vertical').checked) ? 'vertical' : 'horizontal';
   var num_ads = parseInt(document.getElementById('max_text_group_ads').value);
   if ( adDir == 'horizontal' ) {
      if ( parseInt(document.getElementById('num_cols').value) ) {
         var columns = parseInt(document.getElementById('num_cols').value);
         var blank = (num_ads <= columns) ? columns - num_ads : (num_ads%columns) ? columns - (num_ads%columns) : 0;
         var rows = ((num_ads+blank)/columns);
      }
      var linkSample = '<table width="100%">';
      for (i=0;i<rows;i++) {
         linkSample += '<tr>';
         for (j=0;j<columns;j++) {
            if ((i==(rows-1)) && (j>=columns-blank)) {
               linkSample += '<td class="table_content"></td>';
            } else {
               linkSample += '<td class="table_content"><div><a href="#" class="adhead">Fine Cheeses</a></div><div><a href="#" class="adtext">Specialty cheese, low prices</a></div></td>';
            }
         }
         linkSample += '</tr>';
      }
      linkSample += '</table><br />';
      document.zoneform.text_layout[1].checked = true;
   } else if ( adDir == 'vertical' ) {
      var linkSample = '';
      for (i=0;i<num_ads;i++) {
         linkSample += '<div><a href="#" class="adhead">Fine Cheeses</a></div><div><a href="#" class="adtext">Specialty cheese, low prices</a></div><div><br />';
      }
   }
   linkSample += '<a href="#" class="adhead">Your Ad Here</a></div>';
   document.getElementById('sampleLinks').innerHTML = linkSample;
   colorIt('classic');
}



function _reColorBoxes() {
   for (var i=0; i<_reColorBoxes.arguments.length; i++) {
                oldColor = document.getElementById('colorfield-'+_reColorBoxes.arguments[i]).value;
                sample = document.getElementById('colorsample-'+_reColorBoxes.arguments[i]);
                oldColor=testHex(oldColor);
                if(oldColor=='') {
                        sample.style.backgroundImage = 'url(images/no-color.gif)';
                        sample.style.backgroundPosition = 'center center';
                        sample.style.backgroundColor='transparent';
                } else {
                        sample.style.backgroundImage = '';
                        sample.style.backgroundColor = oldColor;
                }
        }

}

function swap(newAd) {
        //currentAd = 'document.getElementById('ad-size-picker').value';
        // alert(currentAd);
   document.getElementById(current_ad).style.display='none';
   colorIt(newAd);
   document.getElementById(newAd).style.display='block';
   current_ad=newAd;
   if(newAd=="classic"){
      document.getElementById("classic-specs").style.display="block";
      document.getElementById("choose-colors").className="choose-colors-alt";
      document.getElementById("choose-colors-alt").appendChild(document.getElementById('choose-colors'));
      displayBorderBack(false);
   } else {
      document.getElementById("classic-specs").style.display="none";
      document.getElementById("choose-colors").style.display="block";
      document.getElementById("choose-colors").className="choose-colors";
      document.getElementById("choose-colors-pos").appendChild(document.getElementById('choose-colors'));
      displayBorderBack(true);
   }
}

function showClassicSpecs(){
         document.getElementById("classic-specs").style.display="block";
         document.getElementById("choose-colors").style.display="block";
         document.getElementById("choose-colors").className="choose-colors-alt";
         document.getElementById("choose-colors-alt").appendChild(document.getElementById('choose-colors'));
         displayBorderBack(false);
}

function displayBorderBack(show) {
   var disp = (show) ? '' : 'none';
   document.getElementById("colorrow-border").style.display=disp;
   document.getElementById("colorrow-background").style.display=disp;
   document.getElementById("border-cell").style.display=disp;
   document.getElementById("background-cell").style.display=disp;
   document.getElementById("colorrow-url").style.display=disp;
   document.getElementById("url-cell").style.display=disp;
}

function testHex(color) {
   if (color.charAt(0) != '#') { color = '#' + color; }
   if (color.match(/#[0-9A-Fa-f]{6}/)) return color;
   
   // if color is not a proper color, return an empty string
   return '';
}

function showPreview(whichAd, field, color) {
   color=testHex(color);
   var adRef=document.getElementById(whichAd);
   var bgTable = adRef.getElementsByTagName('table');
   var divs = adRef.getElementsByTagName('div'); 
   if (field=='title') {
      var adHeadlines=getElementsByClassName('adhead',whichAd);
      for(var i=0;i<adHeadlines.length;i++) { 
         adHeadlines[i].style.color = color;
      }
   }
   if (field=='text') {
      var adText=getElementsByClassName('adtext',whichAd);
      for(var i=0;i<adText.length;i++) {
         adText[i].style.color = color;
      }
   }
   if (field=='url') {
      var adUrl=getElementsByClassName('adurl',whichAd);
      for(var i=0;i<adUrl.length;i++) {
         adUrl[i].style.color = color;
      }
   }
   if (field=='newurl') {
      var newUrl=getElementsByClassName('newurl',whichAd);
      for(var i=0;i<newUrl.length;i++) {
         newUrl[i].style.color = color;
      }
   }




   if (field=='background') {
      if (color == '') color='transparent';
      bgTable[0].style.background = color;
      if (document.getElementById('adsby-728')) document.getElementById('adsby-728').style.color = (isDark(color)) ? '#FFFFFF' : '#000000';
      if (document.getElementById('adsby-468')) document.getElementById('adsby-468').style.color = (isDark(color)) ? '#FFFFFF' : '#000000';
   }
   if (field=='border') {
	  bgTable[0].style.border = '1px solid '+color;
      if (divs[0]) {
         divs[0].style.backgroundColor = color;
         divs[0].getElementsByTagName('a')[0].style.color = (isDark(color)) ? '#FFFFFF' : '#000000';
      }
      if (whichAd == 'IAB-1' || whichAd == 'IAB-2') {
         img = elem.getElementsByTagName('img');
         if (img[0]) {
            img[0].style.backgroundColor = color;
            if (isDark(color)) {
               if (whichAd == 'IAB-1') img[0].src = 'http://files.adbrite.com/mb/images/adbrite-your-ad-here-leaderboard-w.gif';
               if (whichAd == 'IAB-2') img[0].src = 'http://files.adbrite.com/mb/images/adbrite-your-ad-here-banner-w.gif'; 
            } else {
               if (whichAd == 'IAB-1') img[0].src = 'http://files.adbrite.com/mb/images/adbrite-your-ad-here-leaderboard.gif';
               if (whichAd == 'IAB-2') img[0].src = 'http://files.adbrite.com/mb/images/adbrite-your-ad-here-banner.gif';
            }
         }
      }
   }

   if (document.getElementById('colorfield-border').value.toLowerCase() == document.getElementById('colorfield-background').value.toLowerCase())
      adRef.getElementsByTagName('a')[0].style.textDecoration = 'underline';
   else adRef.getElementsByTagName('a')[0].style.textDecoration = 'none';
}

function colorIt(ad) {
   var brC=document.getElementById('colorfield-border').value;
   set_color('border',brC);
   brC=testHex(brC);
   var bgC=document.getElementById('colorfield-background').value;
   set_color('background',bgC);
   bgC=testHex(bgC);
   var ttC=document.getElementById('colorfield-title').value;
   set_color('title',ttC);
   ttC=testHex(ttC);
   var txC=document.getElementById('colorfield-text').value;
   set_color('text',txC);
   txC=testHex(txC);
   var urC=document.getElementById('colorfield-url').value;
   set_color('url',urC);
   urC=testHex(urC);
   var n1C=document.getElementById('colorfield-newurl').value;
   set_color('newurl',n1C);
   n1C=testHex(n1C);
   //title
   var adHeadlines=getElementsByClassName('adhead',ad);
   for(var i=0;i<adHeadlines.length;i++) {
      adHeadlines[i].style.color = ttC;
   }
   //text
   var adText=getElementsByClassName('adtext',ad);
   for(var i=0;i<adText.length;i++) {
      adText[i].style.color = txC;
   }
   //display url
   var adUrl=getElementsByClassName('adurl',ad);
   for(var i=0;i<adUrl.length;i++) {
      adUrl[i].style.color = urC;
   }

   var newUrl=getElementsByClassName('newurl',ad);
   for(var i=0;i<newUrl.length;i++) {
      newUrl[i].style.color = n1C;
   }

   if(ad!='classic') {
      //background color
      elem=document.getElementById(ad);
      var bgTable = elem.getElementsByTagName('table');
      var divs = elem.getElementsByTagName('div');
      if (bgC=='' || bgC=='none') {
         bgTable[0].style.background = 'transparent';
         if (document.getElementById('adsby-728')) document.getElementById('adsby-728').style.color = '#000000';
         if (document.getElementById('adsby-468')) document.getElementById('adsby-468').style.color = '#000000';
      } else {
         bgTable[0].style.background = bgC;
         if (document.getElementById('adsby-728')) document.getElementById('adsby-728').style.color = (isDark(bgC)) ? '#FFFFFF' : '#000000';
         if (document.getElementById('adsby-468')) document.getElementById('adsby-468').style.color = (isDark(bgC)) ? '#FFFFFF' : '#000000';
      }

      //border color
      if (brC=='' || brC=='none') {
         bgTable[0].style.border = 'none';
      } else {
         if (divs[0]) {
            divs[0].style.backgroundColor = brC;
            divs[0].getElementsByTagName('a')[0].style.color = (isDark(brC)) ? '#FFFFFF' : '#000000';  
         }
         bgTable[0].style.border = '1px solid '+brC;
         if (ad == 'IAB-1' || ad == 'IAB-2') {
            img = elem.getElementsByTagName('img');
            if (img[0]) {
               img[0].style.backgroundColor = brC;
               if (isDark(brC)) {
                  if (ad == 'IAB-1') img[0].src = '/mb/images/adbrite-your-ad-here-leaderboard-w.gif';
                  if (ad == 'IAB-2') img[0].src = '/mb/images/adbrite-your-ad-here-banner-w.gif';
               } else {
                  if (ad == 'IAB-1') img[0].src = '/mb/images/adbrite-your-ad-here-leaderboard.gif';
                  if (ad == 'IAB-2') img[0].src = '/mb/images/adbrite-your-ad-here-banner.gif';
               }
            }
         }
      }
      if (document.getElementById('colorfield-border').value.toLowerCase() == document.getElementById('colorfield-background').value.toLowerCase())
         elem.getElementsByTagName('a')[0].style.textDecoration = 'underline';
      else elem.getElementsByTagName('a')[0].style.textDecoration = 'none';
   }
}

//Get all the elements of the given classname of the given tag.
function getElementsByClassName(classname,elem,tag) {
 if(!tag) tag = "*";
 var elems = document.getElementById(elem);
 var anchs =  elems.getElementsByTagName(tag);
 var total_anchs = anchs.length;
 var regexp = new RegExp('\\b' + classname + '\\b');
 var class_items = new Array()
 
 for(var i=0;i<total_anchs;i++) { //Go thru all the links seaching for the class name
  var this_item = anchs[i];
  if(regexp.test(this_item.className)) {
   class_items.push(this_item);
   }
 }
 return class_items;
}

function get_layout (layout) {
   switch (layout) {
      case '728x90': return 'IAB-1';
                     break;
      case '468x60': return 'IAB-2';
                     break;
      case '120x600': return 'IAB-3';
                     break;
      case '160x600': return 'IAB-4';
                     break;
      case '300x250': return 'IAB-5';
                     break;
      case '336x280': return 'IAB-6';
                     break;
      case 'classic': return 'classic';
                     break;
      default: return 'classic';
                     break;
   }
}

function GiveDec(Hex) { 
      if(Hex == "A") Value = 10; 
      else if(Hex == "B") Value = 11; 
      else if(Hex == "C") Value = 12; 
      else if(Hex == "D") Value = 13; 
      else if(Hex == "E") Value = 14; 
      else if(Hex == "F") Value = 15; 
      else Value = eval(Hex); 
      return Value; 
 } 
 function HexToDec(Input) { 
      Input = Input.toUpperCase(); 
      a = GiveDec(Input.substring(0, 1)); 
      b = GiveDec(Input.substring(1, 2)); 
      c = GiveDec(Input.substring(2, 3)); 
      d = GiveDec(Input.substring(3, 4)); 
      e = GiveDec(Input.substring(4, 5)); 
      f = GiveDec(Input.substring(5, 6)); 
      x = (a * 16) + b; 
      y = (c * 16) + d; 
      z = (e * 16) + f; 
      return('r=' +x+',g='+y+ ',b='+z ); 
 } 
 
 function isDark(hex) {
      hex = hex.slice(1, hex.length);
      rgb = HexToDec(hex).split(',');
      r = (rgb[0]).slice(2,rgb[0].length);
      g = (rgb[1]).slice(2,rgb[1].length);
      b = (rgb[2]).slice(2,rgb[2].length);
      total = (parseInt(r) + parseInt(g) + parseInt(b));
      return (total > 355) ? false : true;
 }

