// Copyright (c) 2006. Adobe Systems Incorporated.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of Adobe Systems Incorporated nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// Global variables:

var gThumbWidth = 30;
var gThumbHeight = 30;
var gBehaviorsArray = [];
var gSlideShowTimer = null;
var gImageLoader = null;

// Register a callback on the thumbnails region so we can show the first
// image in the data set whenever the data changes.

Spry.Data.Region.addObserver("thumbnails", function(nType, notifier, data) {
	if (nType == "onPreLoad")
		StopSlideShow();
	else if (nType == "onPostUpdate")
	{
		StartSlideShow();
		ShowCurrentImage();
	}
});

// Trigger the transition animation from the current image
// being displayed to the image at imgPath.

function SetMainImage(imgPath, width, height, tnID)
{
  var img = document.getElementById("mainImage");
  if (!img)
    return;

  CancelBehavior("mainImage");

  Spry.Utils.SelectionManager.clearSelection("thumbnailSelection");

  if (tnID)
    Spry.Utils.SelectionManager.select("thumbnailSelection", document.getElementById(tnID), "selectedThumbnail");

  if (gImageLoader)
  {
    gImageLoader.onload = function() {};
    gImageLoader = null;
  }

  gBehaviorsArray["mainImage"] = new Spry.Effects.Opacity(img, 0, { duration: 400, steps: 10,
    onComplete: function(b)
	{
      gBehaviorsArray["mainImage"] = new Spry.Effects.Size(img.parentNode, width, height, {duration: 400, steps: 10,
	    onComplete: function(b)
	    {
		  // Use an image loader to make sure we only fade in the new image after
		  // it is completely loaded.
	      gImageLoader = new Image();
		  gImageLoader.onload = function()
		  {
	        img.src = gImageLoader.src;
			gImageLoader = null;
	        gBehaviorsArray["mainImage"] = new Spry.Effects.Opacity(img, 1, { duration: 400, steps: 10, onComplete: function(b) { gBehaviorsArray["mainImage"] = null; }});
		  };
		  gImageLoader.src = imgPath;
	    }
	  });
    }
  });
}

// Cancel the animation behavior of the object with the given id.

function CancelBehavior(id)
{
  if (gBehaviorsArray[id])
  {
    gBehaviorsArray[id].stop();
    gBehaviorsArray[id] = null;
  }
}

// Trigger the animation of the thumbnail growing.

function GrowThumbnail(img, width, height)
{
  Spry.Utils.addClassName(img, "inFocus");
  img.style.zIndex = 150;

  var id = img.getAttribute("id");

  var twidth = Math.floor(width * .75);
  var theight = Math.floor(height * .75);
  var tx = (gThumbWidth - twidth) / 2;
  var ty = (gThumbHeight - theight) / 2;

  CancelBehavior(id);

  gBehaviorsArray[id] = new Spry.Effects.SizeAndPosition(img, tx, ty, twidth, theight,{duration:400,steps:10,onComplete:function(b){gBehaviorsArray[id] = null;}});
}

// Trigger the animation of the thumbnail shrinking.

function ShrinkThumbnail(img)
{
  Spry.Utils.addClassName(img, "inFocus");
  img.style.zIndex = 1;

  var id = img.getAttribute("id");

  CancelBehavior(id);

  gBehaviorsArray[id] = new Spry.Effects.SizeAndPosition(img, 0, 0, gThumbWidth, gThumbHeight, {duration:400,steps:10,onComplete:function(b){gBehaviorsArray[id] = null; Spry.Utils.removeClassName(img, "inFocus");}});
}

// Show the image of the current selected row inside the galleryPhotos data set.

//function ShowCurrentImage()
//{
//  var curRow = galleryPhotos.getCurrentRow();
//  imgwidth = curRow["width"];
//  if (curRow["width"]<=400){
//  SetMainImage("images/" + curRow["file"], curRow["width"], curRow["height"], "tn" + curRow["ds_RowID"]);
//  }
//  else
//  {
//  imgscalepercent = 400/curRow["width"];
//  imgscalewidth = Math.floor(imgscalepercent*curRow["width"]);
//  imgscaleheight = Math.floor(imgscalepercent*curRow["height"]);
//  SetMainImage("images/" + curRow["file"], imgscalewidth, imgscaleheight, "tn" + curRow["ds_RowID"]);
//  }
//}

// Utility function to advance (forwards or backwards) the current selected row
// in galleryPhotos. This has the side effect of "selecting" the thumbnail and image
// of the new current row.

function AdvanceToNextImage(moveBackwards)
{
  var rows = galleryPhotos.getData();
  var curRow = galleryPhotos.getCurrentRow();
  
  if (rows.length < 1)
    return;

  for (var i = 0; i < rows.length; i++)
  {
    if (rows[i] == curRow)
    {
      if (moveBackwards)
        --i;
      else
        ++i;
      break;
    }
  }

  if (!moveBackwards && i >= rows.length)
    i = 0;
  else if (moveBackwards && i < 0)
    i = rows.length - 1;

  curRow = rows[i];
  galleryPhotos.setCurrentRow(curRow["ds_RowID"]);
  ShowCurrentImage();
}

// Start the slide show that runs forwards through all
// the rows in galleryPhotos.

function StartSlideShow()
{
  if (gSlideShowTimer)
    clearInterval(gSlideShowTimer);
  gSlideShowTimer = setInterval(function(){ AdvanceToNextImage(false); }, 6000);
  var playLabel = document.getElementById("playLabel");
  if (playLabel)
  	playLabel.firstChild.data = "Pause";
	playLabel.parentNode.id = "pausebtn";
}

// Kill any slide show that is currently running.

function StopSlideShow()
{
  if (gSlideShowTimer)
    clearInterval(gSlideShowTimer);
  gSlideShowTimer = null;
  var playLabel = document.getElementById("playLabel");
  if (playLabel)
  	playLabel.firstChild.data = "Play";
	playLabel.parentNode.id = "playbutton";
}

function HandleThumbnailClick(id)
{
  StopSlideShow();
  galleryPhotos.setCurrentRow(id);
  ShowCurrentImage();
}
// Blogfusion Code to Handle Form Checking on E-Card
function MM_findObj(n, d) { //v4.01
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && d.getElementById) x=d.getElementById(n); return x;
	}
	
	function YY_checkform() { //v4.70
	//copyright (c)1998,2002 Yaromat.com
	  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
	  for (i=1; i<a.length;i=i+4){
	    if (a[i+1].charat(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
	    o=mm_findobj(a[i].replace(/\[\d+\]/ig,""));
	    o1=mm_findobj(a[i+1].replace(/\[\d+\]/ig,""));
	    v=o.value;t=a[i+2];
	    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
	      if (r&&v.length==0){err=true}
	      if (v.length>0)
	      if (t==1){ //fromto
	        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
	      } else if (t==2){
	        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
	      } else if (t==3){ // date
	        ma=a[i+1].split("#");at=v.match(ma[0]);
	        if(at){
	          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
	          dte=new Date(cy,cm,cd);
	          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
	        }else{err=true}
	      } else if (t==4){ // time
	        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
	      } else if (t==5){ // check this 2
	            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
	            if(!o1.checked){err=true}
	      } else if (t==6){ // the same
	            if(v!=MM_findObj(a[i+1]).value){err=true}
	      }
	    } else
	    if (!o.type&&o.length>0&&o[0].type=='radio'){
	          at = a[i].match(/(.*)\[(\d+)\].*/i);
	          o2=(o.length>1)?o[at[2]]:o;
	      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
	      if (t==2){
	        oo=false;
	        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
	        if(!oo){s+='* '+a[i+3]+'\n'}
	      }
	    } else if (o.type=='checkbox'){
	      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
	    } else if (o.type=='select-one'||o.type=='select-multiple'){
	      if(t==1&&o.selectedindex/1==0){err=true}
	    }else if (o.type=='textarea'){
	      if(v.length<a[i+1]){err=true}
	    }
	    if (err){s+='* '+a[i+3]+'\n'; err=false}
	  }
	  if (s!=''){alert('The required information is incomplete or contains errors:\t\t\t\t\t\n\n'+s)}
	  document.MM_returnValue = (s=='');
	}