var tiles = new Array();
var wallsize = 18; // 19 cells in the wall
var count = 1;

function randOrd(){
  return (Math.round(Math.random())); 
} 

var num = new Array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18');
num = num.sort(randOrd);

var domains = new Array();
var testimonial;
var tNum;

// Merge video arrays so we can create the wall!
for(i = 0; i < testimonials.length; i++) {  
  if(isValidDomain(testimonials[i]['domain'], true)) {
    // Get the tiles for this domain
    tiles = testimonials[i]['tiles'];
    
    // Create the wall from the tiles
    tiles.each(function(item, index) {
        // Create the image 
        var img = new Element('img', { 
          'src' : (image_prefix + 'tiles/' + item),
          'class' : 'tips',
          'title' : testimonials[i]['domain'] + ' :: ' + testimonials[i]['quote'],
		  'id' : i,
          'events': {
              'click': function(){								  
									setTestimonial(img.id);
									$$('.tool-tip').setStyle("visibility","hidden");
                  showPreview(img.id);            
              }  
					 }  
        });            
				
        // Add the new element to the cell!  
        $('cell' + (num[count-1])).grab(img);
        count++;
    });  
  }
}

// Video player flash object
video_player = new FAVideo("video_placeholder", "", 600, 330, { autoLoad:false, autoPlay:false, skinAutoHide: true });
            
// Apply onload events - such as Tips
window.addEvent('domready', function() {

// Function to display testimonial if passed in url
function showPreselected() {
  var url = String(window.location);
  if(url.indexOf('#') > 0) var index = url.indexOf("#");
	else if(url.indexOf('?') > 0) var index = url.indexOf("?");
  
	var data = url.substr(index+1);

  if(data.indexOf("id") == 0)	
	{
    var splitted = data.split("=");
    var vid = splitted[1];
 
    setTestimonial(vid)
  	showPreview();
  }
}
showPreselected();

// Store the titles and text into the tips
function fixtips() {
  $$('.tips').each(function(el){
    var tipContent  = el.getProperty('title');
    var tipBulle  = tipContent.split('::');
    var tipTitle  = tipBulle[0];
    var tipText   = tipBulle[1];
    el.store('tip:title', tipTitle);
    el.store('tip:text', "<span class='left-quote' >&#8220;</span><quote>" + tipText + "</quote><span class='right-quote'>&#8221;</span>");
  });
}
fixtips();

// Display tips
var tips = new Tips($$('.tips'), {
    className: 'tool-tip',
    offset: {'x': -29, 'y': -145}
  });  
});

// Set the current testimonial
function setTestimonial(id) {

  // Set testimonial  
  var testimonial = testimonials[id];
  
  // Set blurb
  var blurb = $('video_screenshot_blurb');
  blurb.innerHTML = " <h4 class='domainname'>" + testimonial['domain'] + "</h4> <p>" + testimonial['content1'] + "</p> <p>" + testimonial['content2'] + "</p> ";

  var quote = $('video_screenshot_quote');
  quote.innerHTML = "<blockquote><span style=\"float: left; font-size:24pt; position: relative; top:-10px; left: 2px;\" class='left-quote'>&#8220;</span><div style=\"width: 490px; margin-left: 24px;\"> " + testimonial['quote'] + "<span class='right-quote'>&#8221;</span></div></blockquote>";
  
  var testimonial_content = $('video_play_testimonial_content');    
  testimonial_content.innerHTML = "<h4 class='domainname'>" + testimonial['domain'] + "</h4> <h4 class='speaker'>" + testimonial['speaker'] + ",</h4> <p>" + testimonial['jobtitle'] + "</p>";
  
  setSolutions(id);
	
  var video_screenshot = $('video_screenshot');
  video_screenshot.setStyle('background',"url('" + testimonial["placeholder"] + "') no-repeat");           

  $$('.tool-tip').setStyle("visibility","hidden");

  tNum = id;
}

function setSolutions(id){
	sol = testimonials[id]['solutions'];
  var printsol = "";  
  var url = "";
    
  // Set solutions
  sol.each(function(item, index) { 
          
          if(item == "Domain Names") url = "/cc/domainname/index";
          else if(item == "Web Hosting") url = "/cc/web-hosting/index";
          else if(item == "Web Design") url = "/cc/website-design/index";
          else if(item == "Search Engine Optimisation") url = "/cc/website-marketing/index";
          
          printsol += "<li><a href=\""+url+"\">"+item+"</a></li>";
        });            
  
  var solutions = $('upsell_solutions');
	var solutions2 = $('upsell_solutions2');
  solutions.innerHTML = "<h4>Solutions:</h4><ul>"+printsol+"</ul>";
	solutions2.innerHTML = "<h4>Solutions:</h4><ul>"+printsol+"</ul>";
}

// Displays video area
function showPreview(id) {
	$$('.tool-tip').setStyle("visibility","hidden");
	var video_content = $('video_content');
  var video_div = $('video');
  var wall_screen = $('wall_screen');
  var wall = $('wall'); 

  var url = String(window.location);
  if(url.indexOf('?') < 1) parent.location.hash = 'id='+id;

	video_content.setStyle('display','block');
  wall_screen.setStyle('opacity','0');
  video_div.setStyle('display','block');
}

// Hides video area
function hidePreview() {
/*	video_player.stop();
	var video_play = $('video_play');
  var video_div = $('video');
  var wall_screen = $('wall_screen');
  wall_screen.setStyle('opacity','1');
  video_div.setStyle('display','none');
	video_play.setStyle('opacity','1');
	video_play.setStyle('display','none');
*/
  window.location="/success-stories";
}

function play() {
  //  testimonial = testimonials[tNum];
  var video_content = $('video_content');
  var video_play = $('video_play');

  // Timeout used to allow time for video swap
  setTimeout('theRest()',300);
  video_content.setStyle('display','none');
  video_play.setStyle('display','block');
}

function theRest()
{
	video_player.load(testimonials[tNum]["video"]);
  video_player.play();
}

 function validate(form) { 
  if (stringtest('name',form.name,form.name.value,'','Please enter your Name')) {return false;}
  if (stringtest('phone',form.phone2,form.phone2.value,'','Please enter your Phone Number')) {return false;}
  if (stringtest('email',form.email,form.email.value,'','Please enter an Email Address')) {return false;}
  if (stringtest('comment',form.comment,form.comment.value,'','Please enter your Story')) {return false;}
  if (booltest('emaildiv',form.email,!isValidEmail(form.email.value),'Please enter a valid Email Address')) {return false;}
  
  return true;
}

$('story_form').addEvent('submit', function () {
  var err = Array();
  var val, title, type;
  $$("input, textarea").each(function(inp) {
    val = inp.getProperty('value').trim();
    title = inp.getProperty('title');
    type = inp.getProperty('type');
    name = inp.getProperty('name');
		bg = inp.getProperty('style');
		fail = "#FFFFB0";
		pass = "white";
		
    var last;
    if(type == 'text' ||  name == 'comment') {
      if(val == title || val == '') {
        err.include('Required fields cannot be left empty');			
				inp.style.background = fail;
		  } else if(name == 'comment' && val != '') {
        inp.style.background = pass;				
      } else if(name == 'email') {
        val = val.toLowerCase();
        inp.setProperty('value', val);
        if(!val.test(/^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,4}$/)) {
          err.include('Please enter a valid email');
					inp.style.background = fail;
					} else { inp.style.background = pass; }
      } else if(name == 'phone2') {
        if(!val.test(/^[-\+\s\.\(\)0-9]{8,}$/)) {
          err.include('Please enter a valid phone number');
					inp.style.background = fail;
          } else { inp.style.background = pass; }  
			} else if(name == 'name') {
        last = (val.contains(' ')) ? val.indexOf(' ') : val.length;
        if(val.substring(0, last).length > 14) {
          err.include('Length of First name is too long(max 14).');
					inp.style.background = fail;
					} else { inp.style.background = pass; }
        }			 
    } else if(type == 'radio') {
      val = '';
      $('story_form').getElements('input[name=' + inp.name + ']').each(function(el) {
        if(el.checked) {
          val = el.get('value');
        }				
      });
      if(val == '') {
        err.include('Please select a ' + title);
      }
    }		 		
  });

  if(!err.getLast()) {
    return true;
  } else {
    msg1 = 'Please resolve the following errors.\n\n';
    var count = 0;
    err.each(function(msg) {
      count++;
      msg1 += count + ". " + msg + '\n'; 
    });
    alert(msg1);
  }
  return false;
});

