function openPopUpWindow(newURL, winName, winHeight, winWidth, center, xPos, yPos)
{
   if (!xPos)
   {
      xPos=0;
   }
   if (!yPos)
   {
      yPos=0;
   }

   if ((parseInt(navigator.appVersion) >= 4 ) && (center))
   {
      xPos = (screen.width - winWidth) / 2;
      yPos = (screen.height - winHeight) / 2;
   }

   args = "width        = " + winWidth + ","
        + "height       = " + winHeight + ","
        + "dialogWidth  = " + winWidth + ","
        + "dialogHeight = " + winHeight + ","
        + "location     = 0,"
        + "menubar      = 0,"
        + "resizable    = 1,"
        + "scrollbars   = 1,"
        + "status       = 0,"
        + "titlebar     = 0,"
        + "toolbar      = 0,"
        + "hotkeys      = 0,"
        + "screenx      = " + xPos + "," //NN Only
        + "screeny      = " + yPos + "," //NN Only
        + "left         = " + xPos + "," //IE Only
        + "top          = " + yPos;      //IE Only

   window.open(newURL, winName, args);
}


/********** BEGIN: screen handling **********/
function jt_valPx(pixels) {
  return pixels + "px";
  }

function jt_moveTo(obj, x, y) {
  obj.style.left = jt_valPx(x);
  obj.style.top = jt_valPx(y);
  obj.style.zIndex = '100';
  }

function jt_Point(x, y) {
  // returns a "Point" object with '.x' and '.y' properties
  this.x = x;
  this.y = y;
  }

function jt_getOffsetXY(obj, findID, point) {
  // 'findID' and 'point' are optional
  // returns 'jt_Point' object with '.x' and '.y' offsets of 'obj' relative to page
  // or relative to 'findID' if 'findID' is used and found as a parent
  if (point) { // re-use when valid; good practice when dragging
    point.x = obj.offsetLeft;
    point.y = obj.offsetTop;
    }
  else point = new jt_Point(obj.offsetLeft, obj.offsetTop);
  var parent = obj.offsetParent;
  while (parent != null) {
    if (findID && (parent.id == findID)) break;
    point.x += parent.offsetLeft;
    point.y += parent.offsetTop;
    parent = parent.offsetParent;
    }
  return point;
  }

function jt_getOffsetX(obj) {
  // returns 'x' coordinate of 'obj'
  var xPos = obj.offsetLeft;
  var parent = obj.offsetParent;
  while (parent != null) {
    xPos += parent.offsetLeft;
    parent = parent.offsetParent;
    }
  return xPos;
  }

function jt_getOffsetY(obj) {
  // returns 'y' coordinate of 'obj'
  var yPos = obj.offsetTop;
  var parent = obj.offsetParent;
  while (parent != null) {
    yPos += parent.offsetTop;
    parent = parent.offsetParent;
    }
  return yPos;
  }

function jt_currStyle(divToRead) {
  // return current (derived) CSS style object
  var cs = divToRead.style;
  if (window.getComputedStyle) cs = window.getComputedStyle(divToRead,null);
  else if (divToRead.currentStyle) cs = divToRead.currentStyle;
  return cs;
  }

function jt_width(divToRead) {
  var wide = jt_currStyle(divToRead).width;
  return (wide = 'auto') ? divToRead.offsetWidth : parseInt(wide);
  }

function jt_height(divToRead) {
  var high = jt_currStyle(divToRead).height;
  return (high = 'auto') ? divToRead.offsetHeight : parseInt(high);
  }
/********** END: screen handling **********/


var myDiv = '';
var myContentStatus = {};
var mySubTabContentStatus = {};
var showLeadReportFromPerf = false;
var showLinkoutReportFromPerf = false;
var showPublisherReportFromPerf = false;
var transactionData;

function showPopUpDiv(fullPath, titleText, divWidth, divHeight)
{
   screenHeight = document.body.clientHeight - 50;
   if(divHeight > screenHeight)
   {
      divHeight = screenHeight;
   }

   if (myDiv)
   {
      return;
   }

   myDiv = new Window('popupWindow', {
                                 width: divWidth,
                                 height: divHeight,
                                 zIndex: 5000,
                                 className: "alphacube",
                                 title: titleText,
                                 draggable: true,
                                 minimizable: false,
                                 maximizable: false,
                                 resizable: false,
                                 destroyOnClose: true,
                                 showEffect: Element.show,
                                 hideEffect: Element.hide,
                                 onClose   : function ()
                                             {
                                                myDiv = null;

                                                if (navigator.userAgent.indexOf('Mac') != -1)
                                                {
                                                   showDiv('graphDiv');
                                                   hideOverlay();
                                                }
                                             }
                                }
                      );

   myDiv.setDestroyOnClose();
   myDiv.setAjaxContent(fullPath, {
                                    method:'post',
                                    onLoading:showIndicator,
                                    onComplete: function ()
                                    {
                                       checkSession();
                                       hideIndicator();

                                       if (navigator.userAgent.indexOf('Mac') != -1)
                                       {
                                          hideDiv('graphDiv');
                                       }
                                    }
                                  },
                                  false, true);
   myDiv.showCenter();
   showOverlay();
}

function showOverlay()
{
   if (navigator.userAgent.indexOf('Mac') != -1)
   {
      showDiv('bannerIframe');
   }
}

function hideOverlay()
{
   if (navigator.userAgent.indexOf('Mac') != -1)
   {
      hideDiv('bannerIframe');
   }
}

function moveIframe(popupObjId)
{
   if (navigator.userAgent.indexOf('Mac') == -1)
   {
      return;
   }

   systemNotePopup = $(popupObjId);

   $('popupIframe').style.left = jt_getOffsetX(systemNotePopup);
   $('popupIframe').style.top  = jt_getOffsetY(systemNotePopup);
}

function hidePopupIframe()
{
   if (navigator.userAgent.indexOf('Mac') == -1)
   {
      return;
   }

   hideDiv('popupIframe');
}

function showPopupIframe(popupObjId)
{
   if (navigator.userAgent.indexOf('Mac') == -1)
   {
      return;
   }

   systemNotePopup = $(popupObjId);

   $('popupIframe').style.left   = jt_getOffsetX(systemNotePopup);
   $('popupIframe').style.top    = jt_getOffsetY(systemNotePopup);
   $('popupIframe').style.height = jt_height(systemNotePopup);
   $('popupIframe').style.width  = jt_width(systemNotePopup);

   showDiv('popupIframe');
}

function checkSession()
{
   // There is a hidden field 'session_timeout_indicator' in login page.
   // If I found this element in the document after an ajax call is performed
   // then it is sure that session is timed out and ajax call returned the login page.
   if($('session_timeout_indicator'))
   {
      // unset the save flag if session timeout.
      // otherwise it will give you alert before redirecting to login page which we dont want to show
      if (typeof saveFlag != 'undefined')
      {
         for(tabName in saveFlag)
         {
            saveFlag[tabName] = false;
         }
      }

      top.location = '/index.php/Login';
   }
}

function goTo(path)
{
   document.location = path;
}

var tabs = Array('campaign','editor','task','note','notes','tasks','events','setup',
                 'networkInfo','anatomy','allocation','log','file','adUnit','statistics',
                 'myCampaign','myPublisher','myAdvertiser','publisher','advertiser','all',
                 'sales','tech','admin','active','inactive','pending','banned','proposed',
                 'testing','contacts','contact','transaction','new','hot','exclusive',
                 'overview','form','creative','campaignReport','leadReport','billingReport','advent',
                 'worksheet','commission','referral','performance','cpa','cps','cpscom','cpl',
                 'publishertransaction','accounting','howitworks','quickstats','mypublishers');

var tabs1 = Array('dashboardTasks','dashboardEvents');

var subTabs = Array('fieldSetup','ruleSetup','routerSetup','subNotes','subTasks',
                     'subEvents','publisherAllocation','AdvertiserAllocation',
                     'defaultPublisherAllocation','subLeads','subClick','subImpression',
                     'subConversion','banner','textLink','hosted','search','email',
                     'other','file','co-reg','copy');

var campaignTabsArray = Array('statisticsContent','anatomyContent','setupContent',
                              'networkInfoContent','transactionContent','allocationContent',
                              'adUnitContent','fileContent','logContent','accountingContent');
// iframe to reload after filtering
var iframeID;

function showTab(divId)
{
   var tabnames = '';

   for(i = 0; i < tabs.length; i++)
   {
      tabnames += tabs[i];
      //alert(tabnames);
      if (document.getElementById(tabs[i]+'Content'))
      {
         document.getElementById(tabs[i]+'Content').style.display = 'none';
      }

      if (document.getElementById(tabs[i]))
      {
         document.getElementById(tabs[i]).className = '';
      }
   }

   if (document.getElementById(divId + 'Content'))
   {
      document.getElementById(divId + 'Content').style.display = 'block';
   }

   if(document.getElementById(divId))
   {
      document.getElementById(divId).className = 'current';
   }
}

function showTab1(divId)
{
   var tabnames = '';

   for(i = 0; i < tabs1.length; i++)
   {
      tabnames += tabs1[i];

      if (document.getElementById(tabs1[i]+'Content'))
      {
         document.getElementById(tabs1[i]+'Content').style.display = 'none';
      }

      if (document.getElementById(tabs1[i]))
      {
         document.getElementById(tabs1[i]).className = '';
      }
   }

   if (document.getElementById(divId + 'Content'))
   {
      document.getElementById(divId + 'Content').style.display = 'block';
   }

   if(document.getElementById(divId))
   {
      document.getElementById(divId).className = 'current';
   }
}

function loadIframe(tabID, iframeID, controllerName)
{
   if (tabID)
   {
      showTab(tabID);
   }

   document.getElementById(iframeID).src = '/index.php/' + controllerName;
}

function loadIframe1(tabID, iframeID, controllerName)
{
   showTab1(tabID);

   document.getElementById(iframeID).src = '/index.php/' + controllerName;
}

function loadIframeInSubTab(tabID, iframeID, controllerName)
{
   if(tabID != '')
   showSubTab(tabID);

   document.getElementById(iframeID).src = '/index.php/' + controllerName;
}

function showCreativeSubTabs(tabID, iframeID, controllerName)
{
   thisBannerDiv    = document.getElementById('bannerDiv');
   thisBannerIframe = document.getElementById('bannerIframe');

   if (thisBannerDiv && thisBannerDiv.style.display != 'none')
   {
      thisBannerDiv.style.display    = 'none';
      thisBannerIframe.style.display = 'none';
   }

   hideDiv('creativeEmail');
   showDiv('creative_offers');
   if(tabID == 'email')
   {
      showDiv('nav3_container');
      document.getElementById('html').className = 'active';
   }
   else
   {
      hideDiv('nav3_container');
   }

   if(tabID == 'html')
   {
      showDiv('nav3_container');
      document.getElementById('html').className = 'active';
      document.getElementById('copy').className = '';
      tabID = '';
   }
   //alert(tabID+' '+ iframeID+' '+ controllerName);
   loadIframeInSubTab(tabID, iframeID, controllerName);
}


function showDiv(id , display)
{
   if (document.getElementById(id))
   {
      document.getElementById(id).style.display = (display)? display : 'block';
   }
}
function hideDiv(id)
{
   if (document.getElementById(id))
   {
      document.getElementById(id).style.display='none';
   }
}

function toggleDiv(id)
{
   if (document.getElementById(id).style.display != 'none')
   {
      document.getElementById(id).style.display = 'none';
   }
   else
   {
      document.getElementById(id).style.display = 'inline';
   }
}


function showSubTab(divId)
{
   var tabnames = '';

   for(i = 0; i < subTabs.length; i++)
   {
      tabnames += tabs[i];

      if (document.getElementById(subTabs[i]+'Content'))
      {
         document.getElementById(subTabs[i]+'Content').style.display = 'none';
      }

      if (document.getElementById(subTabs[i]))
      {
         document.getElementById(subTabs[i]).className = '';
      }
   }

   if (document.getElementById(divId + 'Content'))
   {
      document.getElementById(divId + 'Content').style.display = 'block';
   }

   if(document.getElementById(divId))
   {
      document.getElementById(divId).className = 'current';
   }
}

function openWindow(newURL)
{
   window.open(newURL);
}

function pickDateTime(buttonObj,inputObject)
{
   calendarTop = inputObject.offsetHeight + 2;
   calendarTop = ($('panels') && $('panels').scrollTop)? calendarTop - $('panels').scrollTop : calendarTop;

   calendarObjForForm.setCalendarPositionByHTMLElement(inputObject,0,calendarTop);	// Position the calendar right below the form input

   calendarObjForForm.setInitialDateFromInput(inputObject,'yyyy-mm-dd hh:ii');	// Specify that the calendar should set it's initial date from the value of the input field.

   calendarObjForForm.addHtmlElementReference('myDate',inputObject);	// Adding a reference to this element so that I can pick it up in the getDateFromCalendar below(myInput is a unique key)

   if(calendarObjForForm.isVisible())
   {
      calendarObjForForm.hide();
   }
   else
   {
      calendarObjForForm.resetViewDisplayedMonth();	// This line resets the view back to the inital display, i.e. it displays the inital month and not the month it displayed the last time it was open.
      calendarObjForForm.display();
   }
}

function pickDate(buttonObj,inputObject)
{
   calendarTop = inputObject.offsetHeight + 2;
   calendarTop = ($('panels') && $('panels').scrollTop)? calendarTop - $('panels').scrollTop : calendarTop;

   calendarObjForForm.setCalendarPositionByHTMLElement(inputObject,0,calendarTop);	// Position the calendar right below the form input

   calendarObjForForm.setInitialDateFromInput(inputObject,'yyyy-mm-dd');	// Specify that the calendar should set it's initial date from the value of the input field.

   calendarObjForForm.addHtmlElementReference('myDate',inputObject);	// Adding a reference to this element so that I can pick it up in the getDateFromCalendar below(myInput is a unique key)

   if(calendarObjForForm.isVisible())
   {
      calendarObjForForm.hide();
   }
   else
   {
      calendarObjForForm.resetViewDisplayedMonth();	// This line resets the view back to the inital display, i.e. it displays the inital month and not the month it displayed the last time it was open.
      calendarObjForForm.display();
   }
}

   /* inputArrayis an associative array with the properties
year
month
day
hour
minute
calendarRef - Reference to the DHTMLSuite.calendar object.
*/
function getDateFromCalendar(inputArray)
{
   var references = calendarObjForForm.getHtmlElementReferences(); // Get back reference to form field.

   references.myDate.value = inputArray.year + '-' + inputArray.month + '-' + inputArray.day; // + ' ' + inputArray.hour + ':' + inputArray.minute;

   calendarObjForForm.hide();

}

function loadNotesDiv(pg)
{
   var url  = 'http://adventv2.dev.atlas.evoknow.net/index.php/CampaignLog?cmd=showNotes&pg=' + pg;
   var pars = "";
   var myAJax = new Ajax.Request(url , {method: 'post', parameters: '', onComplete: responseMethod});
}

function responseMethod(response)
{
   checkSession();
   $('notesDiv').innerHTML = response.responseText;
   changeLocation();
}

function changeLocation()
{
   totalImages = document.images.length;

   for(i = 0; i < totalImages; i++)
   {
      if ( document.images[i].src.indexOf('nextpg') != -1 )
      {
         imgObj  = document.images[i];
         linkObj = imgObj.parentNode;
         linkObj.href = "javascript: loadNotesDiv()";
      }
   }
}

function toggleSet(rad,tool)
{
  var type = rad.value;
  if(tool == 'Contact')
  {
     hideDiv('Advertiser');
     hideDiv('Publisher');
     //hideDiv('Motive');
     if(rad.value == 'Advent')
     {
        showDiv('userTypeDiv');
     }
     else
     {
        hideDiv('userTypeDiv');
     }
     if(rad.value == 'Advertiser' || rad.value == 'Publisher')
     {
        showDiv(rad.value);
     }
  }
  else if(tool == 'Note')
  {
      /*hideDiv('Task');
      if(rad.value == 'Task' || rad.value == 'Event')
      showDiv(rad.value); */
      if(rad.value == 'Task')
      {
        showDiv('Date');
        showDiv('AssignTo');
      }

      else if(rad.value == 'Event')
      {
         hideDiv('AssignTo');
         showDiv('Date');
      }

      else
      {
         hideDiv('Date');
         hideDiv('AssignTo');
      }

  }
  else if(tool == 'CampaignNetworkInfo')
  {
      hideDiv('Publisher');
      if(rad.value == 'Select')
      showDiv('Publisher');
  }
}

function showError(errorMessage)
{
   alert(errorMessage);
}

function doSearch(controller , formName , tool)
{
   var url    = '/index.php/' + controller + '?cmd=Search&tool='+ tool;

   var pars   = Form.serialize(document.forms[formName]);
   var myAJax = new Ajax.Request(url , {method: 'post', parameters: pars, onComplete: searchResponse});
}

function doGlobalSearch(controller , searchText)
{
   var valueType  = isNaN(searchText)? 'string' : 'int';
   var url        = '/index.php/' + controller;
   var pars       = 'cmd=search'+controller+'&searchText='+ searchText+'&value_type='+valueType;
   var myAJax     = new Ajax.Request(url , {
                                              method: 'post',
                                              parameters: pars,
                                              onLoading: showIndicator,
                                              onComplete: function (serverResponse)
                                              {
                                                 checkSession();
                                                 hideIndicator();

                                                 response = serverResponse.responseText;

                                                 if(response)
                                                 {
                                                    //alert(response)
                                                    location.href = response;
                                                 }
                                              }
                                           });
}

function searchResponse(serverResponse)
{
   checkSession();

   iframeID = serverResponse.responseText;

   //alert(iframeID)
   //alert($(iframeID))

   if ($(iframeID))
   {
      $(iframeID).src = $(iframeID).src;
   }

   Windows.close("searchWindow");
}

///////////campaign set up section starts//////////////
   var campaignSetUpFields = {};

   campaignSetUpFields.txtCampaignName    = "campaign Name goes here";
   campaignSetUpFields.txtPreviewURL      = "preview URL";

   campaignSetUpFields.cmp_status_proposed    = "false";
   campaignSetUpFields.cmp_status_pending     = "true";
   campaignSetUpFields.cmp_status_testing     = "false";
   campaignSetUpFields.cmp_status_active      = "false";
   campaignSetUpFields.cmp_status_inactive    = "false";

   function checkChangeForSubTab(subTabName,element)
   {
      var subTabObject = eval(subTabName);

      //alert(element.type+" : "+element.value + element.checked);
      var property = element.id;

      var currentValue = element.value;

      if(element.type == 'checkbox' || element.type == 'radio')
      {
         currentValue = element.checked;
      }

      for( fields in subTabObject)
      {
         if(fields == property)
         {
            if(element.type == 'checkbox' || element.type == 'radio')
            {
               var initialValue =  eval(subTabObject[fields]);
            }
            else
               {
                  var initialValue =  subTabObject[fields];
               }
              //alert(initialValue +" : "+ currentValue);
               if( initialValue == currentValue)
               {
                  changeIconForSubTab(subTabObject,'campaignSetupSpan',false);
               }
               else
               {
                  changeIconForSubTab(subTabObject,'campaignSetupSpan',true);
               }
               }
            }
         }

function changeIconForSubTab(subTabObject,spanId,flag)
{
   if(flag)
   {
      setSaveFlag(true);
      var content =  document.getElementById(spanId).innerHTML;
      var stop = content.indexOf("*");

      if(stop>0)
      {
         var content = content.substring(0,stop);
      }
      document.getElementById(spanId).innerHTML = content+'*';
   }
   else
   {
      checkForUndoForSubTab(subTabObject,spanId);
   }
}

   function checkForUndoForSubTab(subTabObject,spanId)
   {
      for( fields in subTabObject)
      {
         var currentValue = document.getElementById(fields).value;
         if(document.getElementById(fields).type == 'checkbox' || document.getElementById(fields).type == 'radio')
         {
            currentValue = document.getElementById(fields).checked;
         }

         if(document.getElementById(fields).type == 'checkbox' || document.getElementById(fields).type == 'radio')
         {
            var initialValue =  eval(subTabObject[fields]);
         }
         else
         {
            var initialValue =  subTabObject[fields];
         }
         if(initialValue != currentValue)
         {
            return false;
         }
      }
      ////eliminating * mark///
      var content =  document.getElementById(spanId).innerHTML;
      var stop = content.indexOf("*");

      //alert(stop);
      if(stop>0)
      {
         var content = content.substring(0,stop);
      }
      document.getElementById(spanId).innerHTML = content;

      setSaveFlag(false);

   }

///////////campaign set up section ends////////////////

/////////////////campaign editor's js ends//////////////////////

function showGraphOptions()
{
   contentWin = new Window('graphOptions',
                              {
                                 height        : 190,
                                 width         : 430,
                                 zIndex        : 5000,
                                 minimizable   : false,
                                 maximizable   : false,
                                 resizable     : false,
                                 className     : "alphacube",
                                 hideEffect    : Element.hide,
                                 showEffect    : Element.show,
                                 destroyOnClose: true
                              }
                          );

   contentWin.setHTMLContent($('graphOptionsDiv').innerHTML);
   contentWin.showCenter(true);
}

function loadGraph(searchOption , graphType)
{
   if (graphType == 'publisher')
   {
      var url = '/index.php/PublisherDashBoard';
   }
   else
   {
      var url = location.href;
   }
   var pars   = 'cmd=loadGraph&searchOption=' + searchOption;
   var target = 'graphDiv';
   var myAJax = new Ajax.Updater( target , url , {
                                                    method: 'get',
                                                    parameters: pars,
                                                    onLoading: showIndicator,
                                                    onComplete: function (serverResponse)
                                                    {
                                                       checkSession();
                                                       hideIndicator();
                                                    }
                                                 }
                                );

   Windows.close('graphOptions');
}

var lastClickedTab;
function loadTabContent(currentId , controllerName, subTab, params)
{
   lastClickedTab = currentId;

   // Currently selected tab will be reloaded if you click on it again
   //alert(controllerName)
   //alert(currentId)
   if(controllerName.match('Accounting'))
   {
      var controllerName = controllerName.split('+');
      //alert(controllerName)
   }
   if($(currentId) && $(currentId).className == 'current')
   {
      if (currentId == 'editor')
      {
         // do nothing if it is advertiser/publisher editor tab
         return false;
      }

      myContentStatus[currentId] = false;

      for( myStatus in mySubTabContentStatus)
      {
         mySubTabContentStatus[myStatus] = false;
      }
   }

   var tabnames = '';

   for(i = 0; i < tabs.length; i++)
   {
      tabnames += tabs[i];

      if (document.getElementById(tabs[i]))
      {
         document.getElementById(tabs[i]).className = '';
         document.getElementById(tabs[i]).title     = '';
      }
   }

   if(document.getElementById(currentId))
   {
      document.getElementById(currentId).className = 'current';

      if (currentId != 'editor')
      {
         document.getElementById(currentId).title     = 'Click to reload this tab.'
      }
   }

   for( myStatus in myContentStatus)
   {
      contentObj = document.getElementById(myStatus+'Content');
      if (contentObj)
      {
         contentObj.style.display = "none";
      }
   }

   if(myContentStatus[currentId] == true)
   {
      document.getElementById(currentId+'Content').style.display = "block";
      return;
   }

   myContentStatus[currentId] = true;

   if (params)
   {
      URLParams = '&' + params;
   }
   else
   {
      URLParams = '';
   }

   if(subTab)
   {
      getDivContent(currentId+'Content' , '/index.php/' + capitalize(controllerName) + '?sub_tab=' + subTab + '&cmd=' + controllerName + capitalize(currentId) + URLParams, 'block');
   }
   else
   {
      if(currentId=='accounting')
      {
         getDivContent(currentId+'Content' , '/index.php/' + capitalize(controllerName[0])+'?cmd=publisherdetailaccountiing'+'&id='+controllerName[1]+'&tool='+controllerName[2] , 'block');
      }
      else
      {
         getDivContent(currentId+'Content' , '/index.php/' + capitalize(controllerName) + '?cmd=' + controllerName + capitalize(currentId) + URLParams, 'block');
      }
   }
}

function loadSubTabContent(currentId , controllerName, campaignId)
{
   var tabnames = '';

   for(i = 0; i < subTabs.length; i++)
   {
      tabnames += subTabs[i];

      if (document.getElementById(subTabs[i]))
      {
         document.getElementById(subTabs[i]).className = '';
      }
   }

   if(document.getElementById(currentId))
   {
      document.getElementById(currentId).className = 'current';
   }

   for( myStatus in mySubTabContentStatus)
   {
      contentObj = document.getElementById(myStatus+'Content');
      if (contentObj)
      {
         contentObj.style.display = "none";
      }
   }

   if(mySubTabContentStatus[currentId] == true)
   {
      document.getElementById(currentId+'Content').style.display = "block";
      return;
   }

   mySubTabContentStatus[currentId] = true;
   getDivContent(currentId+'Content' , '/index.php/' + capitalize(controllerName) + '?cmd=' + controllerName + capitalize(currentId) + '&campaign_id=' + campaignId  , 'block');
}


function getDivContent(toDiv , toURL , showStyle)
{

   //alert(toURL)
   thisBannerDiv    = document.getElementById('bannerDiv');
   thisBannerIframe = document.getElementById('bannerIframe');

   if (thisBannerDiv && thisBannerDiv.style.display != 'none')
   {
      thisBannerDiv.style.display    = 'none';
      thisBannerIframe.style.display = 'none';
   }

   var myAjax = new Ajax.Updater(
   toDiv,
   toURL,
   {
      method:'get',
      parameters: '',
      onLoading: showIndicator,
      onComplete: function(response)
                  {
                     checkSession();

                     if (showStyle)
                     {
                        $(toDiv).style.display = showStyle;
                     }
                     hideIndicator();

                     if (toDiv == 'networkInfoContent')
                     {
                        initNetworkInfo();
                        tinyMCE.execCommand('mceAddControl', false, 'txtDescription');
                     }

                     if (toDiv == 'setupContent' && $('campaignId') && $F('campaignId'))
                     {
                        initCampaignSetupInfo();
                     }


                     if (toDiv == 'transactionContent')
                     {
                        if (showLeadReportFromPerf)
                        {
                           showSubTab('subLeads');
                           document.forms['frmCampaignTransaction'].elements['searchOption'].value = document.forms['frmStatistics'].elements['searchOption'].value
                           loadTransactionContent();
                        }

                        else if (showLinkoutReportFromPerf)
                        {
                           changeTransactionData(transactionData);
                           //loadIframeInSubTab('sub'+transactionData,'campaignTransactionList', 'GridCampaign'+transactionData);
                           loadIframeInSubTab('sub'+transactionData,'campaignTransactionList', 'GridadmincampaignTransection'+transactionData);
                        }

                        else if (showPublisherReportFromPerf)
                        {
                           document.forms['frmPublisherTransaction'].elements['searchOption'].value = document.forms['frmPublisherPerformance'].elements['searchOption'].value
                           changeTransactionData(transactionData);
                           loadIframeInSubTab('sub'+transactionData,'publisherTransactionList', 'GridPublisher'+transactionData);
                        }
                     }

                     // show selected offer at top of list after reload
                     if ($('navMyOffers') && $('navMyOffers').className == 'navOn' && $('subnavpane'))
                     {
                        selectedOffer = $$('#subnavpane li .active')[0].parentNode;
                        $('subnavpane').scrollTop = selectedOffer.offsetTop;
                     }

                     if (toDiv == 'panelsMain')
                     {
                        resizeWindow();
                     }

                     if (toDiv == 'subNav'
                      || toDiv == 'body'
                      || toDiv == 'myOfferList'
                      || toDiv == 'creativeContent'
                      || toDiv == 'campaignReportContent'
                      || toDiv == 'leadReportContent'
                      || toDiv == 'billingReportContent'
                      || toDiv == 'overviewContent'
                      || toDiv == 'howitworksContent')
                     {
                        resizePublisherWindow();
                        return true;
                     }

                     /*****************************************************************/
                     for(var i = 0; i < campaignTabsArray.length; i++)
                     {
                        if (document.getElementById(campaignTabsArray[i]))
                        {
                           document.getElementById(campaignTabsArray[i]).style.display = 'none';
                        }
                     }

                     if (document.getElementById(lastClickedTab+'Content'))
                     {
                        document.getElementById(lastClickedTab+'Content').style.display = 'inline';
                     }

                     for(i = 0; i < tabs.length; i++)
                     {
                        if (document.getElementById(tabs[i]))
                        {
                           document.getElementById(tabs[i]).className = '';
                           document.getElementById(tabs[i]).title     = '';
                        }
                     }

                     if (document.getElementById(lastClickedTab))
                     {
                        document.getElementById(lastClickedTab).className = 'current';
                     }

                     /******************************************************************/

                  }
   });
}

function capitalize(str)
{
   return (str)? str.charAt(0).toUpperCase() + str.substring(1) : null;
}

function showIndicator()
{
   $('ajax_indicator').style.display = 'inline';
}

function hideIndicator()
{
   $('ajax_indicator').style.display = 'none';
}

function loadStatisticsLeadAnalyticContent()
{
   var target = 'leadAnalyticsContent';
   var toURL  = '/index.php/GridCampaignStatisticsleadanalytics';
   var pars   = '';

   var myAjax = new Ajax.Updater(target , toURL, {
                                                    method     :'get',
                                                    parameters : pars,
                                                    onLoading  : showIndicator,
                                                    onComplete : function ()
                                                    {
                                                       checkSession();
                                                       hideIndicator();
                                                    }
                                                 });
}

function loadStatisticsContent(campaignId)
{
   formName   = 'frmStatistics';
   var target = 'statisticsContent';


   var toURL  = '/index.php/' + controllerName;
   var pars   = Form.serialize(document.forms[formName]);

   var myAjax = new Ajax.Updater(target , toURL, {
                                                    method     :'post',
                                                    parameters : pars,
                                                    onLoading  : showIndicator,
                                                    onComplete : function ()
                                                    {
                                                       checkSession();
                                                       hideIndicator();
                                                    }
                                                 });
}

function loadCalendarContent(month,year)
{
   // hardcode. todo: have to remove later
   controllerName = 'DashBoard';
   formName       = '';
   var target = 'calender';


   var toURL  = '/index.php/' + controllerName;
   var pars   = 'cmd=loadCalendar&month='+month+'&year='+year;//Form.serialize(document.forms[formName]);

   var myAjax = new Ajax.Updater(target , toURL, {
                                                    method     :'post',
                                                    parameters : pars,
                                                    onLoading  : showIndicator,
                                                    onComplete : function ()
                                                    {
                                                       checkSession();
                                                       hideIndicator();
                                                    }
                                                 });
}

function reloadIframe(iframeID)
{
   if ($(iframeID))
   {
      $(iframeID).src = $(iframeID).src;
   }
}

function deleteConfirm(msg)
{
   if(msg) msg = '"'+msg+'"';
   else msg = "this entry";
   var agree = confirm('Do you want to permanently delete '+msg+'?');

	return agree?true:false;
}

function savePublisherCampaign()
{
   formName   = 'frmPublisherCampaign';
   var url    = '/index.php/PublisherDashBoard?cmd=savePublisherCampaign';

   var pars   = Form.serialize(document.forms[formName]);
   var myAJax = new Ajax.Request(url , {
                                          method: 'post',
                                          parameters: pars,
                                          onLoading : showIndicator,
                                          onComplete: function()
                                          {
                                             checkSession();
                                             reloadIframe('DashboardCampaignWatchGrid');
                                             hideIndicator();
                                          }
                                       });
   Windows.close('popupWindow');
}

function saveQuickStat()
{
   formName   = 'frmQuickStat';
   var url    = '/index.php/PublisherDashBoard?cmd=saveQuickStat';

   var pars   = Form.serialize(document.forms[formName]);
   var target = 'quick_stats_info';
   var myAJax = new Ajax.Updater(target,url , {
                                          method: 'post',
                                          parameters: pars,
                                          onLoading : showIndicator,
                                          onComplete: function()
                                          {
                                             checkSession();
                                             hideIndicator();
                                          }
                                       });
   Windows.close('popupWindow');
}

function changeGridHeader(header)
{
   $('myContentHeader').innerHTML = header;
}

function checkUrl(element)
{
  var regx   = /^(((http(s?))|(ftp))\:\/\/)((\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)|(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk))(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$/i;

   var myUrl = element.value;
   if(myUrl)
   {
    if( ! regx.exec(myUrl))
      {
         alert("Please Insert Valid Url");
      }
    }
}

function forgotPassword()
{
   formName       = 'frmForgotPassword';
   controllerName = 'forgotPassword';

   // var target = 'fieldSetupContent';
   var toURL  = '/index.php/' + controllerName;
   var pars   = 'cmd=checkEmailAddress&'+ Form.serialize(document.forms[formName]);

   var myAjax = new Ajax.Request(toURL, {
                                                    method     :'post',
                                                    parameters : pars,
                                                    onLoading  : showIndicator,
                                                    onComplete : function ()
                                                    {
                                                       checkSession();
                                                       hideIndicator();
                                                    }
                                                });
}

function showLoginUserCreateWindow(mode)
{
   var formName = document.frmTest;
   showDiv('loginUser');
   hideDiv('createLoginId');
   showDiv('cancelLoginId');
   formName.has_login.value = 'hasLoginId';
   if(mode == 'edit')
   {
      formName.has_login.value = 'newLoginId';
   }
}

function showCancelLoginUserCreateWindow()
{
   var formName = document.frmTest;
   hideDiv('loginUser');
   showDiv('createLoginId');
   hideDiv('cancelLoginId');
   formName.has_login.value = 'contact';
}

function getBrowserName()
{
   if (navigator.userAgent.indexOf('IE') != -1)
   {
      return 'IE';
   }
   else if (navigator.userAgent.indexOf('Firefox') != -1)
   {
      return 'FF';
   }
   else if (navigator.userAgent.indexOf('Safari') != -1)
   {
      return 'SF';
   }
   else
   {
      return 'Other';
   }
}

function getIframeElementById(iframeId , elementId)
{
   iframeObj = document.getElementById(iframeId);

   if (iframeObj)
   {
      iframeElement = iframeObj.contentWindow.document.getElementById(elementId);

      if (iframeElement)
      {
         return iframeElement;
      }
   }

   return null;
}

function searchDashboardByDate(searchOption)
{
   var target = 'DashboardSummary';
   var toURL  = '/index.php/DashBoard';
   var pars   = 'cmd=searchByDate&searchOption=' + searchOption;

   var myAjax = new Ajax.Updater(target , toURL, {
                                                    method     :'get',
                                                    parameters : pars,
                                                    onLoading  : showIndicator,
                                                    onComplete : function (serverResponse)
                                                    {
                                                       //alert(serverResponse.responseText);
                                                       checkSession();
                                                       hideIndicator();
                                                       reloadIframe('DashboardSummary');
                                                       loadGraph();
                                                    }
                                                 });
}

function switchScreen(tabID, iframeID, toolName)
{
   if (tabID)
   {
      showTab(tabID);
   }

   if (tabID == 'overview')
   {
      getDivContent('panelsMain', '/index.php/Accounting?cmd=overview');
   }
   else if(!document.getElementById(iframeID))
   {
      getDivContent('panelsMain', '/index.php/Accounting?cmd=others&toolName=' + toolName);
   }
   else
   {
      document.getElementById(iframeID).src = '/index.php/Gridaccounting' + toolName;
   }
}

function togglepaymentMethodDiv(value)
{
   if(value == 'Paypal')
   {
     showDiv('paypalDiv');
     hideDiv('directDepositDiv');
   }

   if(value == 'Direct Deposit')
   {
     hideDiv('paypalDiv');
     showDiv('directDepositDiv');

   }

   if(value == 'Check')
   {
     hideDiv('paypalDiv');
     hideDiv('directDepositDiv');
   }


}

var URLCount = 1;
function addAnotherSite()
{
   if(URLCount < 3)
   {
      URLCount++;
   }

   showDiv('url_container_'+URLCount);

   if (URLCount ==3)
   {
     hideDiv('add_another_link');
   }
}

function selectAllUrl(theField) {

  var tempval=document.getElementById('referral_url');
  tempval.focus();
  tempval.select();
}

function hideurlContainer(counter)
{
   hideDiv('url_container_'+counter);
   URLCount--;

   if (URLCount < 3)
   {
     showDiv('add_another_link');
   }
}

function changeStates()
{
   var formName = document.frmTest;
   if(formName)
   {
      var country = formName.listCountry.value;
   }
   var formNamePublisher = document.frmPublisherSignup;

   if(formNamePublisher)
   {
      country = formNamePublisher.listCountry.value;
      formName = formNamePublisher;
   }
   if(country =='US')
   {
      formName.txtState.style.display = 'none';
      formName.listState.style.display = 'block';
   }
   else
   {
      formName.txtState.style.display = 'block';
      formName.listState.style.display = 'none';
   }
}

function showLogoImage()
{
   var arVersion = navigator.appVersion.split("MSIE");
   var version = parseFloat(arVersion[1]);
   alert(document.getElementById('logo_image'));
   document.getElementById('logo_image').src = '/view/common/images/advent_logo.png';
}


function showImagePreview(ImageID, fileSrc)
{
   imageObj     = document.getElementById('imageID');
   bannerDiv    = document.getElementById('bannerDiv');

   var originalPicture = new Image();
   originalPicture.src = fileSrc;

   var originalPictureHight = originalPicture.height;
   var originalPictureWidth = originalPicture.width;

   var leftPos  = 0;
   var topPos   = 0;

   leftPos = jt_getOffsetX($(ImageID)) + 100;
   topPos  = jt_getOffsetY($(ImageID));
   topPos  = ($('bodyMainContainer') && $('bodyMainContainer').scrollTop)? topPos - $('bodyMainContainer').scrollTop : topPos;

   topPos = topPos - originalPictureHight / 4;

   if (bannerDiv)
   {
      bannerDiv.style.top     = topPos;
      bannerDiv.style.left    = leftPos;

      imageObj.src            = fileSrc;
      bannerDiv.style.display = 'block';
   }
}

function hideImagePreview()
{
   bannerDiv    = document.getElementById('bannerDiv');
   bannerImage  = document.getElementById('imageID');

   if (bannerDiv)
   {
      bannerDiv.style.display    = 'none';
      bannerImage.src            = "";
   }
}
