/** 
 * Javascript components of Dreamgirl 3
 *
 * What's dreamgirl? www.meetdreamgirl.com
 *
 * Not available for reuse without permission.
 *
 * Some functions within this file are reused from the public domain
 *
 * (c) Papercut Media 2005
 *
 */

/* Reveal Item */

var xmllock;
var submitlock = false;
var myid;

function dgBuildIframe(id,url,IFrameObj) {
  if (!document.createElement) {return true};
  var IFrameDoc;
        
        
       
  if (!IFrameObj && document.createElement) {
    // create the IFrame and assign a reference to the
    // object to our global variable IFrameObj.
    // this will only happen the first time 
    // callToServer() is called
   try {
         var tempIFrame=document.createElement('iframe');
         myid = id+"Frm";      
           tempIFrame.setAttribute('id',myid);
	   tempIFrame.setAttribute('border',0);
	   tempIFrame.setAttribute('frameborder','no');
           tempIFrame.setAttribute('scrolling','no');
           tempIFrame.setAttribute('class','dgInlineForm');
           tempIFrame.frameborder = 'no';
           tempIFrame.src = url;
           parentelement = document.getElementById(id);
           tempIFrame.style.visibility = 'hidden';  
           IFrameObj = parentelement.appendChild(tempIFrame);

        
              if (document.frames) {
                // this is for IE5 Mac, because it will only
                // allow access to the document object
                // of the IFrame if we access it through
                // the document.frames array
        
                IFrameObj = document.frames[myid];
              } else {
                IFrameObj = document.getElementById(myid);
              }

         } catch(exception) {
              // This is for IE5 PC, which does not allow dynamic creation
              // and manipulation of an iframe object. Instead, we'll fake
              // it up by creating our own objects.
              iframeHTML='\<iframe id="'+id+'" style="';
              iframeHTML+='border:0px;';
              iframeHTML+='width:0px;';
              iframeHTML+='height:0px;';
              iframeHTML+='"><\/iframe>';
              document.body.innerHTML+=iframeHTML;
              IFrameObj = new Object();
              IFrameObj.document = new Object();
              IFrameObj.document.location = new Object();
              IFrameObj.document.location.iframe = document.getElementById(id);
              IFrameObj.document.location.replace = function(location) {
                this.iframe.src = location;
              }
    }
  }
  
    return false;

}

/* Runs asynchronous call to processor */
function dgCallToProcessor(url) {
        loadXMLDoc(url);
}

var xmlhttp;
var bodyoffset;
var snapback_x;
var snapback_y;

/**
   Sends an asynchronous request to a url and alerts on state change (known in the
   buzzworld as AJAX 
*/
function loadXMLDoc(url)
{
        if (xmllock) {
                window.alert("Please wait for current action to finish");
        } else {
        
        // set the xml lock to prevent two actions running simultaneously
        xmllock = true;
        
        // code for Mozilla, etc.
        if (window.XMLHttpRequest)
          {
          xmlhttp=new XMLHttpRequest()
          xmlhttp.onreadystatechange=xmlhttpChange
          xmlhttp.open("GET",url,true)
          xmlhttp.send(null)
          }
        // code for IE
        else if (window.ActiveXObject)
          {
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
            if (xmlhttp)
            {
            xmlhttp.onreadystatechange=xmlhttpChange
            xmlhttp.open("GET",url,true)
            xmlhttp.send()
            }
          }
          
         }
}


function xmlhttpChange()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
  {
  // if "OK"
  if (xmlhttp.status==200)
    {
    displayInlineFeedback("Success");
    
    // unlock the xml action lock
    xmllock = false;
    
    // null point the ajax object, we don't need it any more
    xmlhttp = null;

    // TODO: just reload affected section of document
    document.location.reload();
    }
  else
    {
    displayInlineFeedback("There was a problem with your request: "+xmlhttp.status);
    xmlhttp = null;
    }
  }
}


/**
 * Destroys all previously loaded edit forms on page (called by close action)
 */
function clearFrames() {
        editframes = getElementsByAttribute('class','dgInlineForm');
        for (i = 0; i < editframes.length; i++) {

                myparent = editframes[i].parentNode.getAttribute('id');
                buttonparent = myparent + 'Button';
                myParentNode = document.getElementById(buttonparent).parentNode;
                myParentsParentNode = myParentNode.parentNode;
                
                classSwitch('remove',myParentsParentNode,'dgActiveElement');

                var garbageFrame = editframes[i].parentNode.removeChild(editframes[i]);
                
                // set the frame pointer to null to assist with garbage collection as removechild 
                // leaves the reference in place
                garbageFrame = null;      
        }
        
        // clear the global submit lock so another action can take place
        submitlock = false;
}



/**
 * Reveals inline edit form for dreamgirl
 *
 * @param id DOM id of parent element of iframe (the element you're clicking from)
 * @param url url of edit form
 * @highlight boolean if we want to change the highlight class of parent element
 */
 
function dgRevealForm(id,url,highlight) {


        myid = id+'Frm';
        thisframe = document.getElementById(myid);
        
        // if running on an existing frame, toggle it off
        if (thisframe) {

                myframe = document.getElementById(id).removeChild(thisframe);
                myframe = null;
                
                jumpTo(snapback_x,snapback_y,20);
                document.getElementById(id+'Button').setAttribute('class','dgButtonLink');
                
                if (highlight) {                
                myParent = document.getElementById(id+'Button').parentNode;
                
                myParentsParent = myParent.parentNode;
                classSwitch('remove',myParentsParent,'dgActiveElement');
                }
                
             //   thisframe.style.display='none';
        } else {
                
                clearFrames();             
                thisid = id;
                
                bodyheight = document.body.scrollHeight;
                bodywidth = document.body.scrollWidth;

                if (submitlock) {
                        alert("Dreamgirl is currently working. Please wait until she is ready");
                } else {
                // set Button Style
                document.getElementById(id+'Button').setAttribute('class','dgInlineButtonActivated');
                if (highlight) {
                myParent = document.getElementById(id+'Button').parentNode;
                myParentsParent = myParent.parentNode;
                classSwitch('add',myParentsParent,'dgActiveElement');
                }
                if (dgBuildIframe(id,url)) {
                        window.alert("Could not build iframe for "+id);
                        return true;
                } 
                }
        }
}


/* User-side feedback */
function displayInlineFeedback(message) {
        var pd = document.getElementById("dgProgressDiv");
// window.alert("hiding progress div");        
        // if the progress div is displaying from a submit action, remove it and set to null
        if (pd) {
            var gPd = document.body.removeChild(pd);
            gPd = null;
        }
        pd = null;
   //     window.alert("showing feedback div");
        // create feedback div               
        var tempFeedback=document.createElement('DIV');
        if (tempFeedback) {
        tempFeedback.setAttribute('id','dgInlineFeedback');
        tempFeedback.style.display='none';

        feedbackObj = document.body.appendChild(tempFeedback);

        if (feedbackObj) {
                wrapDiv = document.getElementById('wrap');
                if (wrapDiv) {
                document.getElementById('wrap').style.display='none';
                }
                feedbackObj.style.display='block';
        } 
        
        } else {
                alert(message);
        }
}


function feedbackCompleted() {
        displayInlineFeedback("Success"); 
	// a plain reload appears to crash safari on complex pages, we need to maybe garbage collect here?

    var clearElementProps = [
        'data',
        'onmouseover',
        'onmouseout',
        'onmousedown',
        'onmouseup',
        'ondblclick',
        'onclick',
        'onselectstart',
        'oncontextmenu'
    ];
/*
        var el;
        var doc = window.parent.document;
        if (doc) {
        var nodes = doc.childNodes;
        if (nodes) {
        for(var d = 0; d < nodes.length;d++){
            for(var c = clearElementProps.length;c--;){
                nodes[d][clearElementProps[c]] = null;
            }
        }
	}
	}
*/	
	window.parent.location.replace(window.parent.location.href);
}




function getElementsByAttribute(attr,val,container)
{
        container = container||document;
        var all = container.all||container.getElementsByTagName('*');
        var arr = [];
        for(var k=0;k<all.length;k++)
        if(all[k].getAttribute(attr) == val)
        arr[arr.length] = all[k]
        return arr
} 

function resizeFrame(documentEl) {
if (myid) {
       document.getElementById(myid).style.height = (documentEl.body.scrollHeight) + "px";
              document.getElementById(myid).style.width = (documentEl.body.scrollWidth) + "px";
}
}

function resizeFrameTo(height,width) {
        if (myid) {
        document.getElementById(myid).style.height = height+"px";
        document.getElementById(myid).style.width = width+"px";
        }
}


// Selects the first non hidden form element
function focusElement(elementSet,i) {
        if (!i) {
                i = 0;
        }
        if (elementSet[i].getAttribute('type') == 'hidden') {
                if (i < elementSet.length) {
                        focusElement(elementSet,(i + 1));
                        return true;
                }
        } else {
                elementSet[i].focus();
                return false;
        }
}
		
function revealMe(documentEl) {
 
    resizeFrame(documentEl);
    if (myid) {
        mydiv = window.document.getElementById(myid);
        mydiv.style.visibility = 'visible';
        if (documentEl.forms.length) {
                focusElement(documentEl.forms[0].elements);
        }
       
        if (mydiv.offsetTop) {
                snapback_x = document.body.scrollLeft;
                snapback_y = document.body.scrollTop;
                var xPos = findPosX(mydiv);
                if (xPos < 0) {
                    mydiv.style.marginLeft = "0px";
                    
              
                }
                jumpTo(xPos,findPosY(mydiv),20);
        }
        }


}


function initMe() {
  //      initFileUploads();
        window.parent.preloadImages();
        window.parent.revealMe(document); 
}

function resizeText(element,enlarge) {
        element = document.getElementById(element);
        if (element) {
                element.style.height = (element.offsetHeight + enlarge)+"px";
        }
        window.parent.resizeFrame(document);
}

        function revealByParent() {
                pWin = window.parent;
                if (pWin) {
                        pWin.revealMe(document)
                } else {
                        alert("no parent");
                }
        }
        
function jumpTo(x,y,ms) {

        me_y = document.body.scrollTop;

        var timer = 0;
        
        if (y > me_y) {
           diff = (y - me_y);
           increment = Math.round(diff / ms);
 
           for (i = me_y; i <= y; i = (i + increment)) {
                setTimeout("window.scrollTo(" + x + "," + i + ")",1);
                timer ++;
           }
        } else if (y < me_y) {
            diff = (me_y - y);
            increment = Math.round(diff / ms);
           for (i = me_y; i >= y; i = (i - increment)) {
               setTimeout("window.scrollTo(" + x + "," + i + ")",1);
                timer ++;
           }                           
        } else {
                window.scrollTo(x,y);
        }
}




function destroyMe() {
        window.parent.clearFrames();
}

function processMe() {

        collapseToProgress();
        window.parent.submitlock = true;
        
        myForm = document.forms[0];
        myForm.submit();
}


function collapseToProgress() {
     var docdiv = document.getElementById("main");
     progressdiv = document.createElement("div");
     progressdiv.setAttribute('id','dgProgressDiv');
     docdiv.style.visibility = "hidden";   
     progress = document.body.appendChild(progressdiv);
}    

var preloaded = false;
function preloadImages() {
        if (!preloaded) {
                images = new Array();
                images[0] = "choose-hit.gif";
                images[1] = "choose-over.gif";
                images[2] = "close-click.gif";
                images[3] = "close-over.gif";
                images[4] = "save-click.gif";
                images[5] = "save-over.gif";
                images[6] = "success.png";
                images[7] = "success.gif";
                images[8] = "dreaming.gif";
                imageObj = document.createElement('img');
                for (i=0;i < images.length;i++) {
                        imageObj.src = "http://dev.papercutmedia.com/sodastream/dreamgirl/images/" + images[i];
                }
                preloaded = true;
         }
}


/* CONTRIB FUNCTIONS - NOT PART OF DG LICENSE */

/* FROM http://www.onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html 


a
defines the action you want the function to perform.
o
the object in question.
c1
the name of the first class
c2
the name of the second class
Possible actions are:
add
adds class c1 to the object o.
remove
removes class c1 from the object o.
check
test if class c1 is already applied to object o and returns true or false.

*/
function classSwitch(a,o,c1)
{
  switch (a){

    case 'add':
      if(!classSwitch('check',o,c1)){
      o.className+=o.className?' '+c1:c1;
      
      }
    break;
    case 'remove':
    
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
      
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}


/**
From http://www.quirksmode.org/dom/inputfile.html

Creates consistent file input fields across browsers
*/

function initFileUploads()
{
        var fakeFileUpload = document.createElement('div');
        fakeFileUpload.className = 'fakefile';
        newinput = document.createElement('input');
        fakeFileUpload.appendChild(newinput);
        var image = document.createElement('img');
       
        classSwitch('add',image,'fakeFileButton');      image.src='http://dev.papercutmedia.com/sodastream/dreamgirl/images/choose.gif';
        fakeFileUpload.appendChild(image);
        var x = document.getElementsByTagName('input');
        for (var i=0;i<x.length;i++)
        {
                if (x[i].type != 'file') continue;
                if (x[i].parentNode.className != 'fileinputs') continue;
                x[i].className = 'file hidden';
                var clone = fakeFileUpload.cloneNode(true);
              
                x[i].parentNode.appendChild(clone);
                x[i].relatedElement = clone.getElementsByTagName('input')[0];
                x[i].onchange = x[i].onmouseout = function () {
                        this.relatedElement.value = this.value;
                }
        }
}

function findPosX(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 findPosY(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;
}



/* Eye Candy */

function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
 
    return true;
} 

//change the opacity for different browsers 
function changeOpac(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
}

