function openParentWindow(url) {
    top.location.href = url
}

$(document).ready(function(){
	setInputTextBoxesClass();
	initGallery();
	initMenu();
   if($('.ajax-fc-container').length) {
	$(".ajax-fc-container").captcha();
   }
   if ( $.browser.webkit || $.browser.mozilla || $.browser.opera || $.browser.msie ) {
	$('.rounded').corners();
   }
});





function setInputTextBoxesClass() {
	$('input').each(function(){
		if ($(this).attr('type') == 'text') $(this).addClass('textinput');
		if ($(this).attr('type') == 'checkbox') $(this).addClass('checkboxinput');
		if ($(this).attr('type') == 'submit') $(this).addClass('submitinput');
	});
}


/*--- menu function ---*/
function initMenu(){
	var im = new Array;
	$('.menu-holder').children().each(function(){
		var _box = $(this).children('.dropdown');
		var _fullw = 0;
	    _box.children('ul').children().each(function(){
			_fullw += $(this).outerWidth(true);
		})
		_fullw += 1;
		_box.attr('fullw', _fullw);
		_box.css({display:'none'});
		var _arrow = $(this).children('.sticky_arrow');
		_arrow.click(function(){
			$('.sticky_arrow').each(function(){
				$(this).parent().attr('className', $(this).parent().attr('className').replace(/ sticky/, ""))
			}); 
			if (_box.parent().attr('className').indexOf('sticky') == -1)  _box.parent().attr('className', _box.parent().attr('className') + " sticky")
			$('.dropdown').each(function(){
				if ($(this).parent().attr('className').indexOf('sticky') == -1) $(this).width(0).css('display', 'none');
			});
		})
		var key = _box.attr('id');
		im[key] = _box.css('background-image');
		$(this).mouseenter(function(){
			key = _box.attr('id');
			_box.attr('className', 'dropdown top');
			if ($(this).attr('className').indexOf('sticky') == -1) {
			if(_box.is(':hidden')){
				_box.css({visibility: 'hidden', display:'block'});
				_box.children().width(_box.children().width());
				_box.css({width:0, visibility: 'visible'});
			}
			_box.css('background-image', 'none');
			_box.stop().animate( {width: _box.attr('fullw') }, 300, function() { $(this).children().width('auto');_box.css('background-image', im[key]); });
			}
		}).mouseleave(function(){
			_box.attr('className', 'dropdown');
			if ($(this).attr('className').indexOf('sticky') == -1) {
			if(!_box.is(':animated')){
				_box.children().width(_box.children().width());
			}
			_box.stop().animate({width: 0}, 300, function(){
				$(this).css({display:'none', width:'auto'}).children().width('auto');
			});};
		});		
	});
	var sticky = $('.menu-holder .sticky');
	_sticky_box = sticky.children('.dropdown');
	sticky.children('.dropdown').stop().animate( {width: _sticky_box.attr('fullw') }, 300, function() { $(this).children().width('auto'); });
}



/*--- fade gallery function ---*/
function initGallery(){
	$('.gallery-body').each(function(){
		var _img = $('<img />');
		var _info = $('<div class="info"></div>');
		$(this).children('.image').append(_img).append(_info);
		var btn_h = $(this).find('.gallery-nav .holder ul');
		var _btn = btn_h.find('a');
		var _a = _btn.index(_btn.filter('.active:eq(0)'));
		var _dir = 1;
		if(_a == -1) _a = 0;
		_btn.removeClass('active').eq(_a).addClass('active');
		_btn.attr('target','_new');
//		_img.attr('src', _btn.eq(_a).attr('linkto')).attr('alt', _btn.eq(_a).attr('rel'));
//		_img.click(function(){window.location.href = _btn.eq(_a).attr('linkto')});
		_img.click(function(){window.open(_btn.eq(_a).attr('href'))});
		_info.html(_btn.eq(_a).attr('rel'));
		_btn.click(function(){
			changeEl(_btn.index(this));
			$('.gallery-nav .action').click();
			return false;
		});
		$(this).find('.gallery-nav .prev').click(function(){
			if(_a > 0) changeEl(_a - 1);
			return false;
		});
		$(this).find('.gallery-nav .next').click(function(){
			if(_a < _btn.length - 1) changeEl(_a + 1);
			return false;
		});
		$(this).find('.gallery-nav .action').click(function() {
			toggleInterval(toggleAction($(this)));
			return false;
		});
		var t_p;
		var t_m;
		var btn_h_w = _btn.parent().outerWidth(true)*_btn.length;

		function changeEl(_ind){
			if(_ind != _a){
				if (_ind >= _btn.length || _ind < 0 ) {_dir = _dir * -1; _ind = _ind + (2*_dir);}
				t_p = _btn.eq(_ind).position().left;
				if(t_p >= btn_h.parent().width() || t_p<0){
				t_m = _ind*btn_h.children().outerWidth();
					if(btn_h_w - t_m < btn_h.parent().width()) btn_h.animate({marginLeft: -btn_h_w + btn_h.parent().width()}, { queue:false, duration:500});
					else btn_h.animate({marginLeft: -_ind*btn_h.children().outerWidth(true)}, { queue:false, duration:500});
				}
				_img.attr('src', _btn.eq(_ind).attr('linkto')).attr('alt', _btn.eq(_ind).attr('rel')).attr('name', _btn.eq(_ind).attr('name'));
//				_img.click(function(){window.location.href = _btn.eq(_ind).attr('linkto')});
				_info.html(_btn.eq(_ind).attr('rel'));
				_btn.eq(_a).removeClass('active');
				_btn.eq(_ind).addClass('active');
				_a = _ind;
			}
		}
		function toggleAction(object) {
		var objectStart = false;
		      if( object.hasClass('pause') ) {object.addClass('play'); object.removeClass('pause');}
			else if( object.hasClass('play') ) {object.addClass('pause'); object.removeClass('play'); objectStart=true;}
			return objectStart;
		}
		var galleryInterval=false;
		function toggleInterval(begin) {
		      if(galleryInterval) {window.clearInterval(galleryInterval); galleryInterval=false;}
		      else {
			galleryInterval = window.setInterval( function() { nb = $(this).find('.gallery-nav .prev'); nb.click(changeEl(_a + _dir)); } , 3000);
			      if(begin) {$(this).find('gallery-nav .prev').click(changeEl(_a+_dir));}
		   }
		}
		toggleInterval();
	});
}

var flashvars = {pathToXML:"/layout/set/flash_xml/content/view/full/2"};

var params = {
	wmode:"transparent"
};
var attributes = { 
	id:"emcswf",
	name:"emcswf"
};

function getSWF(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) return window[movieName];
	else return document[movieName];		
}

function SwfSeekPetalWithIndex(theIndex) {
	getSWF("emcswf").SwfSeekPetalWithIndex(theIndex);
}
function SwfMouseOverPetalWithIndex(theIndex) {
	getSWF("emcswf").SwfMouseOverPetalWithIndex(theIndex);
}
function SwfMouseOutPetalWithIndex(theIndex) {
	getSWF("emcswf").SwfMouseOutPetalWithIndex(theIndex);
}

var ranValidation = false;
function merge_fields(mailresultsto, formNode) {
	if (literal_formname != '') {
		literal_formname = '';
		return true;
	}
	var fname=$(formNode).attr('name');
	var v_code=2;
if(fname=="contact_form"||fname=="enewsletter"||fname=="rfp"||fname=="meeting_form")
{

 if(validatecode()==true){
               v_code=1;        
                      }else{
					
                         v_code=0;
                         }
}
if(v_code==0)	
{
 
return false;
}
      if(!validateForm( $(formNode) )) {return false;}
	  
	var out = '';
	$(formNode).find('.mergeme').each( function() {
		myname = $(this).parent().find('label').html();
		$(this).css('display', 'none');
		out += myname + ' ' + $(this).getValue() + "\r\n";

	})
	$('#00N30000000zvep').setValue(out);
	mail_fields(mailresultsto, formNode);
	return false;
}

var literal_formname = '';
function mail_fields(mailresultsto, formNode) {
	if (literal_formname != '') {
		literal_formname = '';
		return true;
	}
	var fname=$(formNode).attr('name');
	var v_code=2;
if(fname=="contact_form"||fname=="enewsletter"||fname=="rfp"||fname=="meeting_form")
{

 if(validatecode()==true){
               v_code=1;        
                      }else{
					 
                         v_code=0;
                         }
}
if(v_code==0)	
{

return false;
}
	if (!ranValidation) {
		if (!validateForm($(formNode))) {
			return false;
		}
	}

	var mailout = '';
	$(formNode).find('.mailme').each( function() {
		if (literal_formname == '') {
			literal_formname = $(this).parent().parent().attr('name');
		}
		

		myname = '';
		startme = $(this).parent();

		while (myname == '' || myname == null) {
			myname = startme.find('label').html();
			startme = startme.parent();
			if(!startme || startme == null ) {
				myname = 'Unknown Data';
			}
		}

		if (myname.indexOf(':') == -1) {
			myname = myname + ":";
		}

		mailout += myname + ' ' + $(this).getValue() + "<br />";
	});

	$.post("/literalforms/process", { 'txt' : mailout, 'mailresultsto' : mailresultsto }, function(data){submitForm(data)} );

	return false;
}

function submitForm(data) {
	myform = document.forms[literal_formname];
	sfout = '';
	$(myform).find(':input').each(function(){
		sfout += $(this).attr('name');
		sfout += ":";
		sfout += $(this).getValue();
		sfout += "\r\n";
	}) 
	$.post("/literalforms/log", { 'txt' : sfout });
	if(typeof document.forms[literal_formname].submit=="function")
	document.forms[literal_formname].submit();
	else if(typeof document.forms[literal_formname].submit.click=="function")
	document.forms[literal_formname].submit.click();
}

function validateForm(formObject) {
	var invalidForm = false;

	formObject.find('.mailme').each(function() {
		if($(this).hasClass('required') && !invalidForm) {
			invalidForm = !$(this).getValue();
		}
	});

	if (invalidForm) {
		var emptyRequiredFields = [];
		formObject.find('.required').each(function() {
			if(!$(this).getValue()) {
				emptyRequiredFields.push( $(this).parents('div.linewrapper').find('label').text().replace(/\*\s*/,'').replace(/[:]/,'') );
			}
		});
		window.alert("Required Fields Missing:\n\t" + emptyRequiredFields.join("\n\t"));
	} else {
		invalidForm = !validateCaptcha(formObject);
	}

	if (!invalidForm) {
		ranValidation=true;
	}

	//var code_v=validatecode();

	return !invalidForm;
}
function validatecode()
{
	var isValidate = false;
			$.ajax({
			type: "POST",
			url: "/extension/emc/design/emc/session.php",
			cache: false,
			async:false,
			data:{
			"reg_code": $('#reg_code').val()
			},
			success: function(msg) {

				//alert(msg);
			if(msg=="1"||msg==1){
				isValidate = true;	

			}else{
			alert("Please enter a valid verification code");
			isValidate = false;	
			document.URL=location.href;
			}

			}
			});
			return isValidate;

}

function validateCaptcha(formObject) {
var captchaValue = formObject.find("input[name=captcha]").getValue();
    if(formObject.find('.ajax-fc-container').length && captchaValue) {
	var validCaptcha = $.ajax({
		type:"POST",
		url:"/afc/captcha",
		async:false,
		data:"captcha="+captchaValue
	}).responseText;
      if( !Boolean(Number(validCaptcha)) ) {return true;}
   } else if(formObject.find('.ajax-fc-container').length) {
	//window.alert("Please varify that you are human.");
	
	return true;
   }
	return true;
}



function uploadifyFile(inputID, fileLinkID) {
   $('input#filename').css('display','none');
   $(inputID).fileUpload({
    'uploader'	  : '/extension/emc/design/emc/flash/uploader.swf',
    'script'  	  : '/extension/emc/design/emc/upload.php',
    'cancelImg'   : '/extension/emc/design/emc/images/cancel.png',
    'auto'     	  : true,
    'folder'      : '/extension/emc/design/emc/files',
    'scriptData'  : {'prop':'value'},
    'onSelect'	  : function() {
		var emailAddress = encodeURIComponent($('#email').val());
		$(inputID).fileUploadSettings('scriptData','&emailAddress=' + emailAddress);
	},
    'onComplete'  : function(evt, qid, file, resp, data) {
		$('embed#fileInputUploader').css('visibility','hidden');
		$('input#filename').css('display','inline');
		$('input#filename').attr('value', file.name);
	//	$(fileLinkID).attr('value', 'http://www.emcvenues.com'+file.filePath);
		$(fileLinkID).attr('value', 'http://www.emcvenues.com'+resp);
	}
   });
/*
    'onSelect'	  : function() {
	var emailAddress = encodeURIComponent($('#email').val());
window.alert(emailAddress);
	$(inputID).fileUploadSettings('scriptData','&emailAddress='+emailAddress);
   },
	$('input[name=email]').bind('focus', function(){
window.alert('Test');
	      if($(this).val()) {
	var emailAddress = encodeURIComponent($(this).val());
	window.alert('&email=' + emailAddress);
		$(inputID).fileUploadSettings('scriptData','&emailAddress='+emailAddress);
	   }
	});
*/

}


function uploadifyFile3(inputID, fileLinkID) {
   $('input#filename').css('display','none');
   $(inputID).fileUpload({
    'uploader'	  : '/extension/emc/design/emc/flash/uploader.swf',
    'script'  	  : '/extension/emc/design/emc/upload.php',
    'cancelImg'   : '/extension/emc/design/emc/images/cancel.png',
    'auto'     	  : true,
    'folder'      : '/extension/emc/design/emc/files',
    'scriptData'  : {'prop':'value'},
    'onSelect'	  : function() {
		var emailAddress = encodeURIComponent($('#email').val());
		
		var scriptDataString = "";
		var fileCode = $.md5(emailAddress + randomChar(5));
		scriptDataString = '&emailAddress=' + emailAddress;
		scriptDataString += '&fileCode=' + fileCode;
		$(inputID).fileUploadSettings('scriptData', scriptDataString);
		
		$(fileLinkID).attr('value', 'http://www.emcvenues.com/extension/emc/design/emc/getAttachment.php?fileCode='+fileCode);
	},
    'onComplete'  : function(evt, qid, file, resp, data) {
		if($('embed#fileInputUploader').length > 0){
			$('embed#fileInputUploader').css('visibility','hidden');
		}
		
		if($('object#fileInputUploader').length > 0){
			$('object#fileInputUploader').css('visibility','hidden');
		}
		$('input#filename').css('display','inline');
		$('input#filename').attr('value', file.name);
	//	$(fileLinkID).attr('value', 'http://www.emcvenues.com'+file.filePath);
		//$(fileLinkID).attr('value', 'http://www.emcvenues.com'+resp);		
	}
   });
/*
    'onSelect'	  : function() {
	var emailAddress = encodeURIComponent($('#email').val());
window.alert(emailAddress);
	$(inputID).fileUploadSettings('scriptData','&emailAddress='+emailAddress);
   },
	$('input[name=email]').bind('focus', function(){
window.alert('Test');
	      if($(this).val()) {
	var emailAddress = encodeURIComponent($(this).val());
	window.alert('&email=' + emailAddress);
		$(inputID).fileUploadSettings('scriptData','&emailAddress='+emailAddress);
	   }
	});
*/

}


function uploadifyFile2(inputID, fileLinkID) {
   $('input#filename').css('display','none');
	$(inputID).uploadify({
		'uploader': '/extension/emc/design/emc/flash/uploadify.swf',
		'script': 'http://file.emcvenues.com/extension/emc/design/emc/upload.php?id=123',
		/*'script': '/extension/emc/design/emc/upload.php',*/
		'scriptData'  : {'prop':'value'},
		'cancelImg': '/extension/emc/design/emc/images/cancel.png',
		'auto': true,
		/*'multi': true,*/
		/*'fileDesc': 'Image Files',
		'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg;*.txt',*/
		/*'queueSizeLimit': 90,*/
		'sizeLimit': 4000000,
		'buttonText': 'BROWSE',
		'folder': '/extension/emc/design/emc/files',
		/*'folder': 'uploads',*/
		'onSelect' : function() {
			var emailAddress = encodeURIComponent($('#email').val());
			//$(inputID).uploadifySettings('scriptData','&emailAddress=' + emailAddress, true);
			$(inputID).uploadifySettings2('scriptData','&emailAddress=' + emailAddress);
			//$(inputID).uploadifySettings('scriptData', {'emailAddress':emailAddress}, true);
		},
		'onComplete'  : function(evt, qid, file, resp, data) {
			$('object#fileInputUploader').css('visibility','hidden');
			$('input#filename').css('display','inline');
			$('input#filename').attr('value', file.name);
			$(fileLinkID).attr('value', 'http://file.emcvenues.com'+resp);
		}					
	});

}



$(document).ready(function(){
	$("#pageflip").hover(function() { //On hover...
		$("#pageflip img").stop()
			.animate({ //Animate and expand the image and the msg_block (Width + height)
				width: '357px',
				height: '369px'
			}, 500);
		$(".msg_block").stop()
			.animate({ //Animate and expand the image and the msg_block (Width + height)
				width: '357px',
				height: '358px'
			}, 500);
	} , function() {
		$("#pageflip img").stop() //On hover out, go back to original size 50x52
			.animate({
				width: '70px',
				height: '72px'
			}, 220);
		$(".msg_block").stop() //On hover out, go back to original size 50x50
			.animate({
				width: '70px',
				height: '70px'
			}, 200); //Note this one retracts a bit faster (to prevent glitching in IE)
	});
});


function randomChar(l) {
	var x="123456789poiuytrewqasdfghjklmnbvcxzQWERTYUIPLKJHGFDSAZXCVBNM";
	var tmp="";
	for(var i=0;i< l;i++) {
		tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
	}
	return tmp;
}
