/*Exported from jQuery.extends */
jQuery.extend({
	part : 
	function(str, i, separator) 
	{
		//console.log(this);
		if(!separator)	
			separator = ':';
		if(!i)	
			i = 0;
			
		var parts = str.split(separator);
		if (parts.length <= i)
			return false;
		return parts[i];
	}
});


jQuery.fn.extend({
	get_part :
	function(i, aName, separator)
	{
		if(!i)	
			i = 0;
		if(!aName)
			aName = 'id';
		if(!separator)	
			separator = ':';
		return jQuery.part($(this).attr(aName), i, separator);
	}
});


jQuery.extend({
	chunk : 
	function(str, chunk, separator) 
	{
		//console.log(this);
		if(!separator)	
			separator = ':';
		if(!chunk)	
			chunk = 0;
			
		chunks = str.split(separator);
		return chunks[chunk];
	}
});


jQuery.fn.extend({
	chunkId :
	function(chunk, separator)
	{
		return jQuery.chunk($(this).attr('id'), chunk, separator);
	}
});



jQuery.extend({
	sendPostForm: 
	function($form, $element, addData, callback) {
		
		var url = $form.attr('action');
		var post = {};
		var params = $form.serializeArray();
		
		jQuery.each(params, function(i, obj){
			post[obj.name] = obj.value;
		});
		
		if(typeof(addData == 'object')) {
			for(add in addData) {
				post[add] = addData[add];
			}
		}
		
		$element.load(url, post, callback);
		
		return true;
		
	}
});


jQuery.fn.extend({
	sendPostForm: 
	function($form) {
	
		var $element = $(this);
		var url = $form.attr('action');
		var post = {};
		var params = $form.serializeArray();
		
		jQuery.each(params, function(i, obj){
			post[obj.name] = obj.value;
		});
		
		$element.load(url, post);
		return true;
		
	}
});

function init_comments() {
	if (!$("#comments").length)
		return;
	$("#comments").init_bbcode({
			form_name: 'COMMENTS_FORM', 
			text_name: 'DATA[COMMENT]',
			bbcode_buttons:	'.insert_bbcode'
	});
	$(".s-msg-reply").click(function(){
		var parent = $(this).parents("div.info").get(0);
		var parent_id = '#' + $(parent).attr("id");
		$("#COMMENT").html('[quote=' + $("#AUTHOR_" + $(parent).attr("id")).text() + ']' + $("#SOURCE_" + $(parent).attr("id")).text() + '[/quote]');
		$("#comment_PARENT_ID").attr("value", $("#ID_" + $(parent).attr("id")).text());
		$("#comment_LEVEL").attr("value", parseInt($("#LEVEL_" + $(parent).attr("id")).text() + 1));
		$("#comment_PARENT_ID").removeAttr("disabled");
		$("#comment_LEVEL").removeAttr("disabled");
		$("#form-comment-add").insertAfter('#comment' + $("#ID_" + $(parent).attr("id")).text());
		$(".s-msg-reply, .s-msg-add, .s-msg-top").hide();
		$("#form-comment-add").show();
		return false;
	});
	
	$(".s-msg-add").click(function(){
		$("#comment_PARENT_ID").attr("disabled", "disabled");
		$("#comment_LEVEL").attr("disabled", "disabled");
		$("#comment_PARENT_ID").attr("value", "");
		$("#comment_LEVEL").attr("value", "");
		$("#COMMENT").html("");
		$("#form-comment-add").insertAfter('#comments_form_start_position');
		$(".s-msg-reply, .s-msg-add, .s-msg-top").hide();
		$("#form-comment-add").show();
		return false;
	});
	$(".s-msg-cancel").click(function(){
		$("#comment_PARENT_ID").attr("disabled", "disabled");
		$("#comment_LEVEL").attr("disabled", "disabled");
		$("#comment_PARENT_ID").attr("value", "");
		$("#comment_LEVEL").attr("value", "");
		$("#COMMENT").html("");
		$("#form-comment-add").hide();
		$("#form-comment-add").insertAfter('#comments_form_start_position');
		$(".s-msg-reply, .s-msg-add, .s-msg-top").show();
		return false;
	});
}


function init_after_login_return() {
	$('.after_login_return').click(function() {
		//alert("You should login");
		setCookie('after_login_return_url',document.location.href,'','/');
		//location.href="/login/";
	});
}

function init_after_logout_return() {
	$('.after_logout_return').click(function() {
		//alert("You should login");
		setCookie('after_logout_return_url',document.location.href,'','/');
		//location.href="/login/";
	});
	$('.after_logout_return2home').click(function() {
		//alert("You should login");
		setCookie('after_logout_return_url',$("SPAN#SITEHOME").text(),'','/');
		//location.href="/login/";
	});
}

function init_non_auth_message() {
	$(".non_auth").click(function(){
		alert($(this).attr("title"));
		location.href = $(this).attr("href");
	});
}

function init_gallery() {
	//if (typeof(serialScroll) != "undefined") {
		jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
			return -c * ((t=t/d-1)*t*t*t - 1) + b;
		};
		jQuery(function( $ ){
			$('div.gallery_full_list').serialScroll({
				//target:'.gallery_full_list',
				items:'li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
				prev:'.gallery_nav_prev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
				next:'.gallery_nav_next',// Selector to the 'next' button (absolute too)
				axis:'x',// The default is 'y' scroll on both ways
				//navigation:'#greybox_m img.nav_first, #navigation_hidden a, #greybox_m img.nav_last',
				duration:700,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
				force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
				
				//queue:false,// We scroll on both axes, scroll both at the same time.
				//event:'click',// On which event to react (click is the default, you probably won't need to specify it)
				//stop:false,// Each click will stop any previous animations of the target. (false by default)
				//lock:true, // Ignore events if already animating (true by default)		
				//start: 0, // On which element (index) to begin ( 0 is the default, redundant in this case )		
				//cycle:true,// Cycle endlessly ( constant velocity, true is the default )
				//step:1, // How many items to scroll each time ( 1 is the default, no need to specify )
				//jump:false, // If true, items become clickable (or w/e 'event' is, and when activated, the pane scrolls to them)
				//lazy:false,// (default) if true, the plugin looks for the items on each event(allows AJAX or JS content, or reordering)
				//interval:1000, // It's the number of milliseconds to automatically go to the next
				//constant:true, // constant speed
				
				onBefore:function( e, elem, $pane, $items, pos ){
					 //those arguments with a $ are jqueryfied, elem isn't.
					e.preventDefault();
					if( this.blur )
						this.blur();
				},
				onAfter:function( elem ){
					//'this' is the element being scrolled ($pane) not jqueryfied
				}
			});
		});
	//}
}



function init_on_focus_replace() {
	$.each($('.on_focus_replace'),function(i,obj){
		if(!$(obj).attr('title').length && $(obj).attr('value').length)
			$(obj).attr('title',$(obj).attr('value'));
		if(!$(obj).attr('value').length)
			$(obj).attr('value',$(obj).attr('title'));
	});		
	$('.on_focus_replace')
		.focus(function() {
			$(this).attr('value',($(this).attr('value')==$(this).attr('title')?'':$(this).attr('value')));
		})
		.blur(function() {
			$(this).attr('value',($(this).attr('value')==''?$(this).attr('title'):$(this).attr('value')));
		});
}

function init_fading_tabs() {
	$.each($('.tabs_listing'),function(i,obj){
		$(obj).innerfade({
			speed: 2000, //tabs switching speed in milliseconds
			timeout: 8000, //timeout between switching on next tab in milliseconds
			containerheight: $(obj).css("height"), //tabs container height (important for absolute positioned containers)
			el: i //the key in the Buffer array for this tabs set
		});
	});

}

function correct_zindex4menu(selector4_zindex_correction){
	$(selector4_zindex_correction).css({'z-index':'30'});
	$(selector4_zindex_correction +' li').css({'z-index':'30'});
	$(selector4_zindex_correction +' li ul').css({'z-index':'40'});
	$(selector4_zindex_correction +' li ul li').css({'z-index':'50'});
}


function get_parent_div_of_class(element, class_name){
	while ($(element).parent().length){
		element = $(element).parent();
		if ($(element).hasClass(class_name))
			break;
	}
	/*while(pp = $(element).parent().length){
		
	}*/
	return element;
}



/////////////////////////////////////
///Mandatory fields validation
////////////////////////////////////


function luhn_check(number) {
	if (number=='4222222222222222') //Work around for Auth.net test card
      	return true;

  // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
  var number=number.replace(/\D/g, '');
 
  // Set the string length and parity
  var number_length=number.length;
  var parity=number_length % 2;
 
  // Loop through each digit and do the maths
  var total=0;
  for (i=0; i < number_length; i++) {
    var digit=number.charAt(i);
    // Multiply alternate digits by two
    if (i % 2 == parity) {
      digit=digit * 2;
      // If the sum is two digits, add them together (in effect)
      if (digit > 9) {
        digit=digit - 9;
      }
    }
    // Total up the digits
    total = total + parseInt(digit);
  }
 
  // If the total mod 10 equals 0, the number is valid
  if (total % 10 == 0) {
    return true;
  } else {
    return false;
  }
}


function isValidCreditCard(type, ccnum) {
	if (!type)
		type = 'VISA';
	re = '';
   if (type == "VISA") {
   		if (ccnum=='4222222222222222') //Work around for Auth.net test card
      		return true;
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MASTERCARD") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "ISRACARD") {
      // Isracard: length 8-9, no known prefix, dashes optional.
      var re = /^\d{0,1}-?\d{4}-?\d{4}$/;
   } else if (type == "DISCOVER") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AMEX") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "DINERS") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   } else if (type == "JCB") {
      // JCB: length 16, prefix 35 , dashes optional.
      var re = /^35-?\d{4}-?\d{4}-?\d{4}$/;;
   }
   if (re=='' || ccnum=='')
   		 return false;
   if (!re.test(ccnum)) return false;
   if (type == "ISRACARD")
   		return true;
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}


function validate_any_form(frm){
	
		$(frm).find("INPUT, SELECT, TEXTAREA, LABEL").removeClass('mandatory_selected');
		$(frm).find("DIV.form_err_message").hide();
		$(frm).find("DIV.form_err_message DIV.checkbox_mandatory_error").hide();
		
		$("INPUT[name='FORM_VALIDATOR']").addClass('mandatory');
		
		var msg = '';
			

		if ($(frm).find("INPUT.mail, INPUT#EMAIL").length){
			email_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

			$(frm).find("INPUT.mail, INPUT#EMAIL").each(function(){
				if(($(this).attr('value')!='')&& !email_filter.test($(this).attr('value'))){
					$(this).addClass('mandatory_selected');
					if (msg=='')
						msg = 'Entered e-mail is wrong';
				}
			});
		}

		$(frm).find("DIV.form_err_message SPAN.form_email_error").hide();
		if (msg!='')
			$(frm).find("DIV.form_err_message SPAN.form_email_error").show();
		

		$(frm).find("DIV.form_err_message SPAN.form_currency_error").hide();	
		$(frm).find("INPUT.currency").each(function(){
			
			if(($(this).attr('value')!='') && (Number($(this).attr('value')).toFixed(2) != $(this).attr('value'))){
				//alert(Number($(this).attr('value')).toFixed(2) + ':' + $(this).attr('value'));
				$(this).addClass('mandatory_selected');
				if (msg!='') msg+="\n<br>";
					msg+= 'Wrong number format for currency field';
				$(this.form).find("DIV.form_err_message SPAN.form_currency_error").show();
			}
		});
		

		$(frm).find("DIV.form_err_message SPAN.form_password_error").hide();		
		$(frm).find("DIV.form_err_message SPAN.form_mandatory_error").hide();		
		$(frm).find("DIV.form_err_message SPAN.form_cc_error").hide();		
		
		if (($(frm).find("INPUT[TYPE=password]").length>1) &&
			$(frm).find("INPUT#PASSWORD1").length &&
			$(frm).find("INPUT#PASSWORD2").length &&
			($(frm).find("INPUT#PASSWORD1").attr('value') != $(frm).find("INPUT#PASSWORD2").attr('value'))
		){

			$(frm).find("INPUT#PASSWORD1").addClass('mandatory_selected');
			$(frm).find("INPUT#PASSWORD2").addClass('mandatory_selected');
			$(frm).find("DIV.form_err_message SPAN.form_password_error").show();
			if (msg) msg+='<br>';
			msg+= 'Passwords do not match, please try again...';
		}
		
		var checkbox_mandatory_error = '';
		var checkbox_mandatory_selected = false;
		$(frm).find("INPUT[TYPE=checkbox].mandatory").each(function(i,obj){
			if(!$(obj).attr('checked')) {
				$(obj).addClass('mandatory_selected');
				$('LABEL[FOR=' + $(obj).attr("id") + ']').addClass('mandatory_selected');
				if ($(obj).attr("title")!='') {
					if (checkbox_mandatory_error) checkbox_mandatory_error+='<br>';
					if (msg) msg+='<br>';
					msg+= checkbox_mandatory_error+= $(obj).attr("title");
				} else {
					checkbox_mandatory_selected = true;
				}
			}
		});
		if (checkbox_mandatory_error.length > 0) {
			if (!$(frm).find("DIV.form_err_message DIV.checkbox_mandatory_error").length)
				$(frm).find("DIV.form_err_message").prepend('<div class="checkbox_mandatory_error"></div>')
			$(frm).find("DIV.form_err_message DIV.checkbox_mandatory_error").html(checkbox_mandatory_error).show();
			$(frm).find("DIV.form_err_message").show();
		}

		if ($(frm).find("INPUT.mandatory[value=''], SELECT.mandatory[value=''], TEXTAREA.mandatory[value='']").length || checkbox_mandatory_selected){
			if (msg) msg+='<br>';
			msg+= 'Please fill up missing fields below';
			$(frm).find("DIV.form_err_message SPAN.form_mandatory_error").show();
		}
		if ($(frm).find("INPUT.mandatory.on_focus_replace, TEXTAREA.mandatory.on_focus_replace").length){
			var err_on_focus_replace = false;
			$(frm).find("INPUT.mandatory.on_focus_replace, TEXTAREA.mandatory.on_focus_replace").each(function(i,obj){
				if($(obj).attr("value") == $(obj).attr("title")) {
					err_on_focus_replace = true;
					$(obj).addClass("mandatory_selected");
				}
			});
			if (err_on_focus_replace) {
				if (msg) msg+='<br>';
				msg+= 'Please fill up missing fields below';
				$(frm).find("DIV.form_err_message SPAN.form_mandatory_error").show();
			}
		}
		if ($(frm).find("INPUT#CC_NUMBER").length && $(frm).find("#CC_TYPE").length &&
			$(frm).find("INPUT#CC_NUMBER").hasClass('mandatory')){
			
			
			$(frm).find("DIV.form_err_message SPAN.form_cc_error").hide();
			cc_v = $(frm).find("INPUT.mandatory#CC_NUMBER").attr('value');
			cc_t = $(frm).find("#CC_TYPE").attr('value');
			if (!isValidCreditCard(cc_t, cc_v) || (cc_t!='ISRACARD' && !luhn_check(cc_v))){
				if (msg) msg+='<br>';
				msg+=' Credit Card is invalid';
				$(frm).find("DIV.form_err_message SPAN.form_cc_error").show();
				$(frm).find("INPUT.mandatory#CC_NUMBER").addClass('mandatory_selected');
			}
		
			
		}
	
		
		if (msg=='')
			return true;
		$(frm).find("INPUT.mandatory[value=''], SELECT.mandatory[value=''], TEXTAREA.mandatory[value='']").addClass('mandatory_selected');
		$(frm).find(".mandatory_selected:first").focus();
		if (!$(frm).find("DIV.form_err_message").length){
			$(frm).prepend('<div class="form_err_message error_mesage">'+msg+'</div>');
		}
		$(frm).find("DIV.form_err_message").show();
		if ($(frm).find("DIV.form_err_message").html()=='')
			$(frm).find("DIV.form_err_message").html(msg);

		return false;
}

function init_form_validation(){
	
	if (!$("FORM:has(INPUT.mandatory)").length)
		return;
	$("INPUT.currency").blur(function(){
		if (($(this).attr('value') != '') && (Number($(this).attr('value')).toFixed(2)!='0.00') && (Number($(this).attr('value')).toFixed(2)!='NaN'))
			$(this).attr('value', Number($(this).attr('value')).toFixed(2));
	});

	$("FORM:has(INPUT.mandatory), FORM:has(SELECT.mandatory), FORM:has(TEXTAREA.mandatory)").submit(function(){
		return validate_any_form(this);
	});
	$("TD.form_title + TD.form_field:has(INPUT.mandatory)").prev().find("SPAN").text('*').css('color','red');
	$("TD.form_title + :not(TD.form_field:has(INPUT.mandatory))").prev().find("SPAN").html('&nbsp; ').css('padding-left','2px');
}

/******* DIALOG RELATED ****************/

function updateTips(t) {
	tips.text(t).effect("highlight",{},1500);
}

		

function checkLength(o,n,min,max) {
	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('ui-state-error');
		updateTips("Length of " + n + " must be between "+min+" and "+max+".");
		return false;
	}
	return true;
}

function checkRegexp(o,regexp,n) {
	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('ui-state-error');
		updateTips(n);
		return false;
	}
	return true;
}

function init_contacts_form_dialog(){
	
	if ($('.contact_login_dialog_open').length){
			$('.contact_login_dialog_open').click(function() {
				alert("You should login to contact the member!");
				setCookie('after_login_return_url',document.location.href,'','/');
				location.href="/login/";
				return false;
			});
		return;
	}
	
	if(!$("#contact_dialog").length)
		return false;

	$('.contact_dialog_open').click(function() {
		$("#SRC_ID").attr("value", $(this).attr("rel"));
		$("#SENDER_NAME").attr("value", $("#CURRENT_USER_NAME").text());
		$("#SENDER_EMAIL").attr("value", $("#CURRENT_USER_EMAIL").text());
		$("#COMMENTS").attr("value", '');
		$('#contact_dialog').dialog('open');
		return false;
	});

	var name = $("#SENDER_NAME"),
		email = $("#SENDER_EMAIL"),
		text = $("#COMMENTS"),
		//captcha = $("#dialog_captcha"),
		allFields = $([]).add(name).add(email).add(text);//.add(captcha);
			
	$("#contact_dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 430,
		modal: true,
		buttons: {
			'Submit': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				bValid = bValid && checkLength(name,"Name",3,50);
				bValid = bValid && checkLength(email,"E-Mail",6,80);
				//bValid = bValid && checkLength(captcha,"Validation Code",5,5);
				bValid = bValid && checkLength(text,"Details",5,255);

				//bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
				// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
				bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. info@welcomebiz.com ");
				/*" ))))*/
				//bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
			
				if (bValid) {
					//$("#post_contact").submit();
					$(this).dialog('close');
					$.post("/mail.php", $("#post_contact").serialize(),function(data){
						if (data) {
							$("#post_contact_confirm").html(data);
							$("#post_contact_confirm").dialog('open');
						}
					});
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.removeClass('ui-state-error');
		}
	});

	$("#post_contact_confirm").dialog({
		bgiframe: true,
		resizable: false,
		height: 50,
		width: 300,
		autoOpen: false,
		modal: true,
		buttons: {
			'OK': function() {
				$(this).dialog('close');
			}
		}
	});

}



function init_mega_menu(){
	var mega_menu_Config = {    
     interval: 100,
     timeout: 100,
     sensitivity: 4,
     over: function () {$(this).addClass("hovering");},
     out: function (){ $(this).removeClass("hovering");}
	}
	$('UL.mega_menu LI').hoverIntent(mega_menu_Config);
}

function init_calendar_selectors(){
	
	if (!$('#calendar_month').length)
		return;	
	if (!$('#calendar_month_selector').length)
		return;
	if (!$('#calendar_year').length)
		return;	
	if (!$('#calendar_year_selector').length)
		return;
		
	$('#calendar_month_selector_close').click(function(){
		$('#calendar_month_selector').hide();
	});
	
	$('#calendar_year_selector_close').click(function(){
		$('#calendar_year_selector').hide();
	});

	$('#calendar_month').click(function (e){
		el = $('#calendar_month_selector');
		el.css('position', 'absolute');
		el.css('left', $(this).offset().left);
		el.css('top', e.pageY - el.height()/2);
		el.show();
	})
	$('#calendar_year').click(function (e){
		el = $('#calendar_year_selector');
		el.css('position', 'absolute');
		el.css('left', $(this).offset().left);
		el.css('top', e.pageY - el.height()/2);
		el.show();
	})
}

function init_categories_index_list() {
	//if (typeof(serialScroll) != "undefined") {
		jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
			return -c * ((t=t/d-1)*t*t*t - 1) + b;
		};
		
		$('div.box_in').serialScroll({
				//target:'.gallery_full_list',
				items:'li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
				prev:'#categories_index_prev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
				next:'#categories_index_next',// Selector to the 'next' button (absolute too)
				axis:'x',// The default is 'y' scroll on both ways
				//navigation:'#greybox_m img.nav_first, #navigation_hidden a, #greybox_m img.nav_last',
				duration:500,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
				force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
				cycle:false, //don't pull back once you reach the end
				//queue:false,// We scroll on both axes, scroll both at the same time.
				//event:'click',// On which event to react (click is the default, you probably won't need to specify it)
				//stop:false,// Each click will stop any previous animations of the target. (false by default)
				//lock:true, // Ignore events if already animating (true by default)		
				//start: 0, // On which element (index) to begin ( 0 is the default, redundant in this case )
				exclude:3,//Exclude n elements before end		
				//cycle:true,// Cycle endlessly ( constant velocity, true is the default )
				step:4, // How many items to scroll each time ( 1 is the default, no need to specify )
				//jump:false, // If true, items become clickable (or w/e 'event' is, and when activated, the pane scrolls to them)
				//lazy:false,// (default) if true, the plugin looks for the items on each event(allows AJAX or JS content, or reordering)
				//interval:1000, // It's the number of milliseconds to automatically go to the next
				//constant:true, // constant speed
				
				onBefore:function( e, elem, $pane, $items, pos ){
					 //those arguments with a $ are jqueryfied, elem isn't.
					e.preventDefault();
					if( this.blur )
						this.blur();
				},
				onAfter:function( elem ){
					//'this' is the element being scrolled ($pane) not jqueryfied
				}
	});
		
	//}
}

function init_date_pickers(){
	//alert($(".date_picker").eq(0).attr('value'));
	$(".date_picker").datepicker({showOn: 'button', buttonImage: 'img/show-calendar.gif', buttonImageOnly: true});
	
}

function copy_paypal_email(){
	if (!$('#PAYPAL_SAMEAS_BILL').attr('checked'))
		return;
	if (!$('#PAY_PAL_EMAIL').length)
		return;
	if (!$('FORM#checkout_form #EMAIL').length){
			alert('Can not find source EMAIL field');
			return false;
	}
	$('#PAY_PAL_EMAIL').attr('value', $('FORM#checkout_form #EMAIL').attr('value'));
}


function use_billing_data4shipping(){
	if (!$('FORM#checkout_form #copydata').length)
		return false;
	if (!$('FORM#checkout_form #copydata').attr('checked'))
		return false;
	return true;
}

function copy_shipping_data(){
	if (!use_billing_data4shipping())
		return false;
	
	$('FORM#checkout_form .form_block#billing').find('INPUT, SELECT, TEXTAREA').each(function(){
		if ($('FORM#checkout_form #SHIP' +  $(this).attr('ID')).length)
			$('FORM#checkout_form #SHIP' +  $(this).attr('ID')).attr('value', $(this).attr('value'));
	});
	$('FORM#checkout_form #SHIPEMAIL').attr('value', $('FORM#checkout_form #EMAIL').attr('value'));
	$('FORM#checkout_form #SHIPCOUNTRY').change();
	return true;
}


function get_shipping_data(){
	if (!$('FORM#checkout_form #delivery').length)
		return;
	prefix = use_billing_data4shipping()?'':'SHIP';
	country_value4ajax = country_value = 'US';
	zip_value = '';
	
	if ($('FORM#checkout_form #'+prefix+'COUNTRY').length)
		country_value4ajax = country_value = $('FORM#checkout_form #'+prefix+'COUNTRY').attr('value');
	if ($('FORM#checkout_form #'+prefix+'ZIPCODE').length)	
		zip_value = $('FORM#checkout_form #'+prefix+'ZIPCODE').attr('value');
	
	if (country_value=='USA')
		country_value4ajax = country_value = 'US';
	if ((country_value!='US') && (country_value!='CA') && (country_value!='UK'))
		country_value = 'INT';
	if (typeof(region_visual_settings[country_value])=='undefined')
		country_value = 'INT';
	if (typeof(region_visual_settings[country_value])=='undefined')
		country_value = 'US';
	if (typeof(region_visual_settings[country_value])=='undefined'){
		alert('Error: shipping setting for country '+ country_value + ' is not found');
		return;
	}
		

	if (region_visual_settings[country_value+'_is_gateway']!='0')
		$('FORM#checkout_form #RESIDENTIAL_SELECTION_BLOCK').show();
	else
		$('FORM#checkout_form #RESIDENTIAL_SELECTION_BLOCK').hide();
	
	if (region_visual_settings[country_value+'_is_breaks']!='0'){
		$('FORM#checkout_form #delivery').hide();
		$('FORM#checkout_form #DELIVERY_BLOCK_TITLE').hide();
	}
	else{
		$('FORM#checkout_form #delivery').show();
		$('FORM#checkout_form #DELIVERY_BLOCK_TITLE').show();
		if (zip_value!=''){
			settings_id = region_visual_settings[country_value];
			is_res = '';
			if ($('FORM#checkout_form #RESIDENTIAL').length && ($('FORM#checkout_form #RESIDENTIAL').attr('checked') || ($('FORM#checkout_form #RESIDENTIAL').attr('TYPE')=='hidden' && ($('FORM#checkout_form #RESIDENTIAL').val()!=0))))
				is_res = '1';
			$('FORM#checkout_form #SHIPPING_METHOD').hide();
			$('FORM#checkout_form #SHIPPING_DEFAULT_STATUS_TEXT').hide();
			$('FORM#checkout_form #SHIPPING_CALCULATING_STATUS_TEXT').show();
			selected = '';
			$.get('/cms/?section=plain_list&ac=shipping_choices_result&MODULE_PARAMS=SS_ID%3D'+settings_id+'%26ENTIRE_LIST_TEMPLATE%3Dcheckout_shipping_list.html%26ITEM_TEMPLATE%3Dcheckout_shipping_item.html%26PAGE_IDX%3D0%26WHERE%3D%26NUMONPAGE%3D100&params[ZIP]='+
		     zip_value + '&params[COUNTRY]='+ country_value4ajax + '&params[RESIDENTIAL]='+ is_res+'&'+Math.random()+selected, 
				function(data) {
					$('FORM#checkout_form #SHIPPING_METHOD').html(data);
					$('FORM#checkout_form #SHIPPING_CALCULATING_STATUS_TEXT').hide();
					$('FORM#checkout_form #SHIPPING_METHOD').show();
				});

			
		}
	}
	
	
}


function init_ask_question(){
	$('#ask_question_open').click(function(){
		$(this).hide();
		$('#ask_question_close').show();
		$('#ask_form_box').show();
		$('DIV.ask_pan').css('background', 'url("../img/ask_pan.png") repeat scroll 0px 59px transparent');
		
	});
	$('#ask_question_close').click(function(){
		$(this).hide();
		$('#ask_question_open').show();
		$('#ask_form_box').hide();
		$('DIV.ask_pan').css('background', 'url("../img/ask_pan.png") repeat scroll 0px 0px transparent');
	});
	
	$('#wp_question_open').click(function(){
		$(this).hide();
		$('#wp_question_close').show();
		$('#white_papers_form').show();
		$('DIV.wp_pan').css('background', 'url("../img/ask_pan.png") repeat scroll 0px 59px transparent');
		
	});
	$('#wp_question_close').click(function(){
		$(this).hide();
		$('#wp_question_open').show();
		$('#white_papers_form').hide();
		$('DIV.wp_pan').css('background', 'url("../img/ask_pan.png") repeat scroll 0px 0px transparent');
	});
	
	
	$('SPAN.left_menu_toplevel_selector').click(function(){
		if ($(this).attr('ID')=='')
			return;
		if($('.sidemenu#sub'+$(this).attr('ID')+':hidden').length){
			$('.sidemenu#sub'+$(this).attr('ID')).show();
			$('DIV.pan#div-'+$(this).attr('ID')).css('background-position', '0px 56px');
		}else{
			$('.sidemenu#sub'+$(this).attr('ID')).hide();
			$('DIV.pan#div-'+$(this).attr('ID')).css('background-position', '0px 0px');
		}
	});
	
}
		

function init_form_popup()
{
	$('.popup_form_wrapper').each(function(idx){
		var $wrapper = $(this);
		var $headerButton = $wrapper.find('.popup_form_header');
		var $formInner = $wrapper.find('.popup_form_inner');
		
		$headerButton.click(function(e){
			var $currWrapper = $(this).parents('.popup_form_wrapper:first');
			
			if($currWrapper.hasClass('popup_form_wrapper_closed')) {
				$currWrapper.removeClass('popup_form_wrapper_closed');
			}
			else {
				$currWrapper.addClass('popup_form_wrapper_closed');
			}
		});
	});
}



/**
* JS Links
**/
$('a.jsLink').live('click', function(e){
e.preventDefault();
});
	
	
//main jquery hook-up function
$(document).ready(
	function() {
		init_form_validation();
		init_comments();
		init_after_login_return();
		init_after_logout_return();
		$(".jqueryui_tabs").tabs();
		
		init_mega_menu();
		init_fading_tabs();
		
		//Patch, that fixes z-index issue. Must be after init_fading_tabs
		correct_zindex4menu('UL.mega_menu');
		
		init_gallery();
		init_on_focus_replace();
		
		//init_date_pickers();
		
		//init_calendar_selectors();
		
		init_categories_index_list();
		init_ask_question();
		init_form_popup();

		if (typeof(on_custom_jquery_init) != 'undefined')
			on_custom_jquery_init();
	}
);

