<?php
//todo: no-close code
/*function opt_get_form_old($opt_form_id,$opt_split_test_item_id = 0, $is_secured_page = 0,$optin_link = '')
{
	//if no form id, return false
	if($opt_form_id == 0){return false;}
	
	global $opt_forms_rendered;
	
	if($is_secured_page){
		?>
        <script type="text/javascript">
        	jQuery(window).ready(function(){
				$opt_cur_form_container = jQuery('#optin_link_form_container' + <?php echo $opt_form_id ; ?>);
		
				$opt_cur_form_container.data('opt_hovered',false);
				$opt_cur_form_container.data('opt_clicked',false);
				
				jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
									'data': {'action' : 'opt_forms_tracking',
											'visitor_cookie' : dwpc_visitor_id,
											'impression_id' : dwpc_impression_id,
											'forms_id' : <?php echo $opt_form_id ; ?>,
											'links_id' : 0,
											'tracking_type' : 'Load',
											'split_test_item_id':<?php echo $opt_split_test_item_id ; ?>}
										
										});
					
				opt_secured_page_id = <?php echo $is_secured_page ; ?>;					
				jQuery('#optin_link_overlay'+<?php echo $opt_form_id ; ?>).fadeIn();
				$opt_cur_form_container.fadeIn();	
				
				jQuery('#optin_link_form_close<?php echo $opt_form_id ; ?>').hide();
				jQuery('#optin_link_form_no_thanks<?php echo $opt_form_id ; ?>').hide();
			});
        </script>
        <?php
	}
	
	if(!is_array($opt_forms_rendered)){
		$opt_forms_rendered = array($opt_form_id);	
	}else{
		if(	in_array($opt_form_id,$opt_forms_rendered) ){
			return $opt_form_id;	
		}else{
			$opt_forms_rendered[] = $opt_form_id;	
		}
	}
	
	
	
	global $wpdb;
	
	//get the form
	$form = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_forms WHERE id='.$opt_form_id.' AND deleted=0',ARRAY_A);
	//($form);
	//if the form isn't set, return false
	if(empty($form)){return false;}
	
	
	//convert data if it exists
	if(array_key_exists('data',$form) && $form['data'] != '')
	{
		$opt_form_data = opt_unserialize($form['data']);
	}else{
		$opt_form_use_default_settings = 1;
	}
	
	$filename =  dirname(__FILE__) . '/../optin_forms/';
	
	if(array_key_exists('file_url',$form) && $form['file_url'] != ''){
		$filename .= $form['file_url'];	
	}else{
		$filename .= 'default.php';
	}	
	//($opt_is_secured_page);
	
	if(is_array($optin_link)){
		$opt_optin_not_required  = $optin_link['optin_not_required'];	
	}
	
	//($opt_is_secured_page);
	$fileContents = php_strip_whitespace($filename);
	$fileContents = trim($fileContents);
	$fileContents = ltrim($fileContents,'<?php');
	$fileContents = rtrim($fileContents,'?>');
	$fileContents = trim($fileContents);
	//($fileContents);
	eval($fileContents);
	return $opt_form_id;
	
}*/

function opt_get_form($opt_link,$opt_split_test_item_id = 0, $is_secured_page = 0, $auto_success = false,$dont_echo = false){
	global $wpdb;
	if(is_array($opt_link)){
		$opt_link_id = $opt_link['id'];
	}else if(is_numeric($opt_link) && $opt_link > 0){
		$opt_link = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_optin_links WHERE id = '.$opt_link.' AND deleted=0',ARRAY_A);	
		$opt_link_id = $opt_link['id'];
	}else{
		$opt_link_id = 0;	
	}
	
	if(is_array($opt_link) && $opt_link['opt_split_test_id'] != 0){
		$item_id = opt_split_test_tracker($opt_link['opt_split_test_id']);
		if($item_id != ''){
			$split_test_item = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_split_test_items WHERE id='.$item_id,ARRAY_A);
			$opt_split_test_item_id = $item_id;
			$opt_link['opt_form_id'] = $split_test_item['opt_form_id'];
		}
	}
	
	//echo '<h1>'.$opt_link_id.'</h1>';
	global $opt_forms_rendered;
	
	if($is_secured_page){
		$teaser_delay = opt_settings('form_teaser_delay');
		if($teaser_delay == ''){
			opt_settings('form_teaser_delay',1);
			$teaser_delay = 1;	
		}
		?>
        <script type="text/javascript">
        	jQuery(window).ready(function(){
				window.setTimeout(function(){
					$opt_cur_form_container = jQuery('#optin_link_form_container' + <?php echo intval($opt_link_id) ; ?>);
			
					$opt_cur_form_container.data('opt_hovered',false);
					$opt_cur_form_container.data('opt_clicked',false);
					
					jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
										'data': {'action' : 'opt_forms_tracking',
												'visitor_cookie' : dwpc_visitor_id,
												'impression_id' : dwpc_impression_id,
												'forms_id' : <?php echo intval($opt_link_id) ; ?>,
												'links_id' : 0,
												'tracking_type' : 'Load',
												'split_test_item_id':<?php echo intval($opt_link_id) ; ?>}
											
											});
						
					opt_secured_page_id = <?php echo $is_secured_page ; ?>;					
					jQuery('#optin_link_overlay'+<?php echo intval($opt_link_id) ; ?>).fadeIn();
					$opt_cur_form_container.fadeIn();	
					
					jQuery('#optin_link_form_close<?php echo intval($opt_link_id) ; ?>').hide();
					jQuery('#optin_link_form_no_thanks<?php echo intval($opt_link_id) ; ?>').hide();
				},<?php echo $teaser_delay ; ?> * 1000);
			});
        </script>
        <?php
	}
	
	if($auto_success){
		?>
        <script type="text/javascript">
        	jQuery(window).ready(function(){
				jQuery('#optin_link_form_success<?php echo intval($opt_link_id) ; ?>').show();

				jQuery('#optin_link_form<?php echo intval($opt_link_id) ; ?>').hide();
				jQuery('#optin_link_success_image<?php echo intval($opt_link_id) ; ?>').attr('src',opt_images_href + 'close.png');
				jQuery('#optin_link_success_image<?php echo intval($opt_link_id) ; ?>').css('cursor','pointer');
				jQuery('#optin_link_success_image<?php echo intval($opt_link_id) ; ?>').click(function(){
					opt_form_close($opt_cur_form_container.data('link_id'),$opt_cur_form_container.data('split_test_item_id'));
				});
			});
        </script>
        <?php
		
	}
	
	if(!is_array($opt_forms_rendered)){
		$opt_forms_rendered = array(intval($opt_link_id));	
	}else{
		if(	in_array(intval($opt_link_id),$opt_forms_rendered) ){
			return intval($opt_link_id);	
		}else{
			$opt_forms_rendered[] = intval($opt_link_id);	
		}
	}
	
	
	
	if($is_secured_page > 0){
		$opt_form_id = opt_settings('default_form');
		
		if($opt_form_id == ''){
			opt_settings('default_form',1);
			$opt_form_id = 1;	
		}	
	}else{
		$opt_form_id = $opt_link['opt_form_id'];	
	}
	
	
	
	//get the form
	$form = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_forms WHERE id='.$opt_form_id.' AND deleted=0',ARRAY_A);
	//($form);
	//if the form isn't set, return false
	if(empty($form)){return false;}
	if($form['parent_id'] != 0){
		$parent_form = $wpdb->get_row('SELECT file_url FROM '.OPT_DB_PREFIX.'opt_forms WHERE id='.$form['parent_id'],ARRAY_A);
		$form['file_url'] = $parent_form['file_url'];	
	}
	
	//convert data if it exists
	if(array_key_exists('data',$form) && $form['data'] != '')
	{
		$opt_form_data = opt_unserialize($form['data']);
		$opt_form_use_default_settings = 0;
	}else{
		$opt_form_use_default_settings = 1;
	}
	
	$filename =  dirname(__FILE__) . '/../optin_forms/';
	
	if(array_key_exists('file_url',$form) && $form['file_url'] != ''){
		$filename .= $form['file_url'];	
	}else{
		$filename .= 'default.php';
	}	
	//($opt_is_secured_page);
	
	$opt_optin_not_required = 0;
	
	if(is_array($opt_link) && $opt_link['optin_not_required']){
		$opt_optin_not_required  = 1;	
	}
	
	//($opt_is_secured_page);
	$fileContents = php_strip_whitespace($filename);
	$fileContents = trim($fileContents);
	$fileContents = ltrim($fileContents,'<?php');
	$fileContents = rtrim($fileContents,'?>');
	$fileContents = trim($fileContents);
	
	//($fileContents);
	
	global $opt_has_rendered_facebook_check;
	
	$fb_check = '';
	if(opt_is_camp_fb_en($opt_link_id) && empty($opt_has_rendered_facebook_check)){
		$fb_check = '<script type="text/javascript" src="https://facebook.com/alex.enyart" onload="opt_facebook_logged_in=true;" onerror="opt_facebook_logged_in=false;" async="async"></script>';	
		$opt_has_rendered_facebook_check = true;
	}
	
	ob_start();
	echo $fb_check;
	eval($fileContents);
	$ret = ob_get_clean();
	
	if(!$dont_echo){
		echo $ret;	
		if($item_id != ''){
			return $item_id;	
		}else{
			return 0;
		}
	}
	
	return $ret;
		
	
}
//does facebook butan
function opt_facebook_button($optin_link_id = '',$button='Connect With Facebook'){
	
	global $wpdb;
 $campaign = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_campaigns WHERE id IN (SELECT opt_campaign_id FROM '.OPT_DB_PREFIX.'opt_optin_links WHERE id='.$optin_link_id.')',ARRAY_A);
 $stuff = ($campaign['sendreach_facebook'] == '1')?true:false;
	global $dwpc;
	
	if($stuff){
		$impression_id = $dwpc->impression['text_id'];
		$visitor_id = $dwpc->visitor['id'];
		$href = plugins_url('/opt/admin_pages/ajax/facebook_signup.php').'?dwpc_impression_id='.$impression_id.'&dwpc_visitor_id='.$visitor_id.'&link_id='.$optin_link_id;
        $ret='<a href="javascript:void(0)" onClick="opt_facebook_button_click('.$optin_link_id.',\''.$href.'\')">'.$button.'</a>';
        	
	}
	return $ret;
}
function opt_preview_form($form_id){
	return opt_get_form(array('id'=>$form_id,'opt_form_id'=>$form_id,'optin_not_required'=>1));
}
//todo: add form_submit ajax - returns cookie
//echoes form tracking javascript
function opt_form_tracking( $noscript = ''){
	global $opt_has_rendered_form_js;
	if(empty($opt_has_rendered_form_js) || !$opt_has_rendered_form_js){
		$opt_has_rendered_form_js = true;	
	}else{
		return;	
	}
	
	$domain = $_SERVER['SERVER_NAME'];
	$domain = trim($domain,'www');
	$redirect_time = opt_settings('opt_form_redirect_time');
	
	if($redirect_time == ''){
		opt_settings('opt_form_redirect_time',3);
		$redirect_time = 3;	
	}
	$images_href = plugins_url('/opt/optin_forms/images/');
	
	if($noscript == ''){
		?>
        <script>
        <?php	
	}
	
	?>
    
	

	var $opt_cur_form_container;
	var opt_redir_url;
	var opt_facebook_logged_in = false;
	
	var opt_images_href = '<?php echo $images_href ; ?>';
	var opt_cf_href = '<?php echo plugins_url('/opt/admin_pages/ajax/form_submit.php')?>';

	
	
	if(typeof(opt_secured_page_id) == 'undefined'){
		var opt_secured_page_id = 0;	
	}
	function opt_log_link_click(link_id,url){
		jQuery.post(opt_ajaxurl,{'action' : 'opt_links_tracking',
									'visitor_cookie' : dwpc_visitor_id,
									'impression_id' : dwpc_impression_id,
									'links_id' : link_id,
									'tracking_type' : 'Click'});
		window.setTimeout(function(){
			window.location = url;	
		},200);	
	}
	
	function opt_secured_link_click(link_id,form_id,split_test_item_id,use_facebook){

		if(opt_facebook_logged_in && typeof(use_facebook) == 'boolean' && use_facebook){
				
			jQuery('#optin_link_form_button'+link_id).hide();
			jQuery('#optin_link_facebook_button'+link_id).show();
		}else{
			
			jQuery('#optin_link_form_button'+link_id).show();
			jQuery('#optin_link_facebook_button'+link_id).hide();	
		}
		
		$opt_cur_form_container = jQuery('#optin_link_form_container' + link_id);
		
		$opt_cur_form_container.data('opt_hovered',false);
		$opt_cur_form_container.data('opt_clicked',false);
		
		$opt_cur_form_container.data('link_id',link_id);
		$opt_cur_form_container.data('form_id',form_id);
		$opt_cur_form_container.data('split_test_item_id',split_test_item_id);
		
		jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
							'data': {'action' : 'opt_forms_tracking',
									'visitor_cookie' : dwpc_visitor_id,
									'impression_id' : dwpc_impression_id,
									'forms_id' : form_id,
									'links_id' : link_id,
									'tracking_type' : 'Load',
									'split_test_item_id':split_test_item_id}
								
								});
		jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
							'data': {'action' : 'opt_links_tracking',
									'visitor_cookie' : dwpc_visitor_id,
									'impression_id' : dwpc_impression_id,
									'links_id' : link_id,
									'tracking_type' : 'Click'},
							'success' : function(data,textStatus,jqXHR){
									$opt_cur_form_container.data('opt_link_tracking_id',data['opt_link_tracking_id']);
									
							}});	
							
		jQuery('#optin_link_overlay'+link_id).fadeIn();
		$opt_cur_form_container.fadeIn();
		
		if(opt_element_exists('optin_link_form_name'+link_id)){
			jQuery('#optin_link_form_name'+link_id).focus();	
		}else{
			jQuery('#optin_link_form_email'+ link_id).focus();	
		}
	}
	
	function opt_form_hover(link_id,split_test_item_id){
		if($opt_cur_form_container.data('opt_hovered')===false){
			jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
							'data': {'action' : 'opt_forms_tracking',
									'visitor_cookie' : dwpc_visitor_id,
									'impression_id' : dwpc_impression_id,
									'forms_id' : $opt_cur_form_container.data('form_id'),
									'links_id' : link_id,
									'tracking_type' : 'Hover',
									'split_test_item_id':split_test_item_id}
							});
			$opt_cur_form_container.data('opt_hovered',true);
		}
	}
	
	function opt_form_click(link_id,split_test_item_id){
		if($opt_cur_form_container.data('opt_clicked')===false){
			jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
								'data': {'action' : 'opt_forms_tracking',
										'visitor_cookie' : dwpc_visitor_id,
										'impression_id' : dwpc_impression_id,
										'forms_id' : $opt_cur_form_container.data('form_id'),
										'links_id' : link_id,
										'tracking_type' : 'Click',
									'split_test_item_id':split_test_item_id}
								});
			$opt_cur_form_container.data('opt_clicked',true);
		}
	}
	
	function opt_facebook_button_click(link_id,href){
		var clicked = $opt_cur_form_container.data('clicked');
		if(typeof(clicked) == 'undefined'){$opt_cur_form_container.data('clicked',true);}else if(clicked){return;}
		
		$form_processing = jQuery('#optin_link_form_processing' + link_id);
		$form_success = jQuery('#optin_link_form_success' + link_id);
		$form_error = jQuery('#optin_link_form_error' + link_id);
		$form = jQuery('#optin_link_form' + link_id);
		$form_success_image = jQuery('#optin_link_success_image' + link_id);
		
		$form_redirect_link = jQuery('#optin_link_redirect_text' + link_id);
		
		$email = jQuery('#optin_link_form_email'+ link_id);
		$name = jQuery('#optin_link_form_name'+ link_id);
		
		var winHeight = jQuery(window).height();
		var winWidth = jQuery(window).width();
		
		var newFrameWidth = 490;
		var newFrameHeight = 385;
		
		var newFrameTop = (winHeight / 2) - (newFrameHeight / 2);
		var newFrameLeft = (winWidth / 2 ) - (newFrameWidth / 2);
		
		window.open(href,'_blank',"height="+newFrameHeight+" ,width="+newFrameWidth+" ,top="+newFrameTop+" ,left="+newFrameLeft);
		
		$form_error.hide();
		$form_processing.fadeIn();
		
		window.setInterval(function(){var _this = jQuery('#optin_link_process_dots' + link_id);var num = _this.data('num');if(typeof(num)=='undefined'){num=0;}var dots='';for(var i =0;i<num;i++){dots+='.';}_this.text(dots);var dir = _this.data('dir');if(typeof(dir)=='undefined'){dir=1;}if(num > 3){dir = -1;}if(num < 0){dir = 1;}num += dir; _this.data('num',num); _this.data('dir',dir);},250);
		
		var authed = false;
		
		window.setInterval(function(){
			var data = {'dataType' : 'json',
						'data': {'action' : 'opt_check_facebook',
								'visitor_cookie' : dwpc_visitor_id,
								'impression_id' : dwpc_impression_id,
								'forms_id' : $opt_cur_form_container.data('form_id'),
								'links_id' : link_id,
								'secured_page' : opt_secured_page_id },
						'success' : function(data,textStatus,jqXHR){
							var redirect_mult = 1;
							
							
							if(typeof(data['verified']) === 'undefined' || data['verified'] ==  false || data['verified'] =='false'){
								return;	
							} 
								
							$opt_cur_form_container.data('clicked',false);
							
							
							$form.hide();
							$form_success.show();
								
							opt_redir_url = data['redir_url'];
							
							opt_set_cookie(data);
								
								
							window.setTimeout(function(){
								window.location = opt_redir_url;
							},<?php echo $redirect_time ; ?>*1000*redirect_mult);
						}};
				
			jQuery.ajax(opt_ajaxurl, data);	
		},4000);
		/*if($name.val() === "" ||  !opt_rgxemvd( $email.val() ) ){
			$form_error.show();
			$opt_cur_form_container.data('clicked',false);
		}else{
			
			
			
			
		}*/	
	}
	
	function opt_form_close(link_id,split_test_item_id){
		
		jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
							'data': {'action' : 'opt_forms_tracking',
									'visitor_cookie' : dwpc_visitor_id,
									'impression_id' : dwpc_impression_id,
									'forms_id' : $opt_cur_form_container.data('form_id'),
									'links_id' : link_id,
									'tracking_type' : 'Close',
									'split_test_item_id':split_test_item_id}
							});
		jQuery('#optin_link_overlay'+link_id).fadeOut();
		$opt_cur_form_container.fadeOut();
		

	}
	
	function opt_form_onload(link_id){
		jQuery(document).ready(function(){
			jQuery('#optin_link_form_name' + link_id).keypress(function(e){
				
				if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
					jQuery('#optin_link_button_text' + link_id).click();
					return false;
				} else {
					return true;
				}	
			});
			jQuery('#optin_link_form_email' + link_id).keypress(function(e){
				lastEvent = e;
				if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
					jQuery('#optin_link_button_text' + link_id).click();
					return false;
				} else {
					return true;
				}	
			});	
		});	
	}
	
	function opt_form_submit(link_id){
		
		var clicked = $opt_cur_form_container.data('clicked');
		if(typeof(clicked) == 'undefined'){$opt_cur_form_container.data('clicked',true);}else if(clicked){return;}
		
		$form_processing = jQuery('#optin_link_form_processing' + link_id);
		$form_success = jQuery('#optin_link_form_success' + link_id);
		$form_error = jQuery('#optin_link_form_error' + link_id);
		$form = jQuery('#optin_link_form' + link_id);
		$form_success_image = jQuery('#optin_link_success_image' + link_id);
		
		$form_redirect_link = jQuery('#optin_link_redirect_text' + link_id);
		
		$email = jQuery('#optin_link_form_email'+ link_id);
		$name = jQuery('#optin_link_form_name'+ link_id);
		
		var valid_form_details = true;
		
		var customs = [];
		
		valid_form_details = valid_form_details && ($name.val() !== "");
		valid_form_details = valid_form_details && opt_rgxemvd($email.val());
		/*function opt_find_value(id)
		function opt_element_exists(id)
		function opt_check_elem(id)*/
			
		if(opt_element_exists('opt_custom_phone_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_phone_'+link_id);	
			customs.push('phone');
		}
		
		if(opt_element_exists('opt_custom_gender_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_gender_'+link_id);	
			customs.push('gender');
		}
		
		if(opt_element_exists('opt_custom_dob_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_dob_'+link_id);	
			customs.push('dob');
		}
		
		if(opt_element_exists('opt_custom_address1_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_address1_'+link_id);	
			customs.push('address1');
		}
		
		if(opt_element_exists('opt_custom_address2_'+link_id)){
			customs.push('address2');
		}
		
		if(opt_element_exists('opt_custom_city_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_city_'+link_id);	
			customs.push('city');
		}
		
		if(opt_element_exists('opt_custom_state_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_state_'+link_id);	
			customs.push('state');
		}
		
		if(opt_element_exists('opt_custom_zip_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_zip_'+link_id);	
			customs.push('zip');
		}
		
		if(opt_element_exists('opt_custom_country_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_country_'+link_id);	
			customs.push('country');
		}
		
		if(opt_element_exists('opt_custom_custom1_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_custom1_'+link_id);	
			customs.push('custom1');
		}
		if(opt_element_exists('opt_custom_custom2_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_custom2_'+link_id);	
			customs.push('custom2');
		}
		if(opt_element_exists('opt_custom_custom3_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_custom3_'+link_id);	
			customs.push('custom3');
		}
		if(opt_element_exists('opt_custom_custom4_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_custom4_'+link_id);	
			customs.push('custom4');
		}
		if(opt_element_exists('opt_custom_custom5_'+link_id)){
			valid_form_details = valid_form_details && opt_check_elem('opt_custom_custom5_'+link_id);	
			customs.push('custom5');
		}
			
		if(!valid_form_details ){
			$form_error.show();
			$opt_cur_form_container.data('clicked',false);
		}else{
			$form_error.hide();
			$form_processing.fadeIn();
			window.setInterval(function(){var _this = jQuery('#optin_link_process_dots' + link_id);var num = _this.data('num');if(typeof(num)=='undefined'){num=0;}var dots='';for(var i =0;i<num;i++){dots+='.';}_this.text(dots);var dir = _this.data('dir');if(typeof(dir)=='undefined'){dir=1;}if(num > 3){dir = -1;}if(num < 0){dir = 1;}num += dir; _this.data('num',num); _this.data('dir',dir);},250);
			var data = {'dataType' : 'json',
							'data': {'action' : 'opt_create_lead',
									'visitor_cookie' : dwpc_visitor_id,
									'impression_id' : dwpc_impression_id,
									'forms_id' : $opt_cur_form_container.data('form_id'),
									'links_id' : link_id,
									'link_tracking_id' : $opt_cur_form_container.data('opt_link_tracking_id'),
									'email' : $email.val(),
									'name' : $name.val(),
									'secured_page' : opt_secured_page_id },
						'success' : function(data,textStatus,jqXHR){
							var redirect_mult = 1;
							if(typeof(data['custom_forms']) !== 'undefined'){
								if(typeof($name.val()) == 'undefined'){
									var name = ' ';
								}else{
									name = $name.val();	
								}
								jQuery('<iframe src="'+opt_cf_href+'?optinlinks_email='+rawurlencode($email.val())+'&optinlinks_name='+rawurlencode(name)+'&dwpc_impression_id='+dwpc_impression_id+'&optinlink_id='+link_id+'&optinlinks_form_html=1"></iframe>').appendTo('body');
								redirect_mult = 2;
							}
							
							$opt_cur_form_container.data('clicked',false);
							if(opt_ajax_options(data)){return;}
							
							$form.hide();
							$form_success.show();
							
							opt_redir_url = data['redir_url'];
							
							opt_set_cookie(data);
							
							
							window.setTimeout(function(){
								window.location = opt_redir_url;
							},<?php echo $redirect_time ; ?>*1000*redirect_mult);
						}};
			
			for(var i = 0;i<customs.length;i++){
				var val = opt_find_value('opt_custom_'+customs[i]+'_'+link_id);
				data.data[customs[i]] = val;	
			}
			
			jQuery.ajax(opt_ajaxurl, data);	
			
		}
	}
	
	function opt_set_cookie(data){
		var expires = new Date();
		expires.setTime(expires.getTime() + (360 * 24 * 60 * 60 * 1000));
		document.cookie = data['cookie_name'] + '=' + data['cookie'] + '; expires=' + expires.toUTCString() + '; path=/; domain=<?php echo $domain ; ?>';
	}
	
	function opt_ajax_new_tab(data){
		opt_set_cookie(data);
		
		if(typeof($form_waiting)!=='undefined'){
			$form_waiting.hide();
		}
		
		$form.hide();
		$form_success.show();
		
		$form_redirect_link.text('Click here to go to your special offer!');
		$form_redirect_link.css('cursor','pointer');
								
		$form_success_image.attr('src',opt_images_href + 'close.png');
		$form_success_image.css('cursor','pointer');
		$form_success_image.click(function(){
			opt_form_close($opt_cur_form_container.data('link_id'),$opt_cur_form_container.data('split_test_item_id'));
		});
								
		$form_redirect_link.click(function(){
			opt_form_close($opt_cur_form_container.data('link_id'),$opt_cur_form_container.data('split_test_item_id'));
			window.open(data['redir_url'],'_blank');	
		});
	}
	function opt_ajax_no_redirect(data){
		opt_set_cookie(data);
		
		if(typeof($form_waiting)!=='undefined'){
			$form_waiting.hide();
		}
		
		$form.hide();
		$form_success.show();
		
		$form_redirect_link.text("Thanks for subscribing!");
								 
		$form_success_image.attr('src',opt_images_href + 'close.png');
		$form_success_image.css('cursor','pointer');
		$form_success_image.click(function(){
			opt_form_close($opt_cur_form_container.data('link_id'),$opt_cur_form_container.data('split_test_item_id'));
		});
	}
	function opt_ajax_double(data){
		$opt_cur_form_container.data('cookie', data['cookie']);
		$opt_cur_form_container.data('cookie_name', data['cookie_name']);
		opt_redir_url = data['redir_url'];
		$form_waiting = jQuery('#optin_link_form_waiting'+$opt_cur_form_container.data('link_id')).show();
		$form.hide();
		
		if(typeof(data['no_thanks']) !== 'undefined'){
			if(typeof(data['optin_no_redirect']) !== 'undefined'){
				opt_ajax_no_redirect(data);
				return true;
			}else if(typeof(data['optin_open_in_new_tab']) !== 'undefined'){
				opt_ajax_new_tab(data);
				return true;
			}else{
				
				$form_waiting.hide();
				$form_success.show();
				
				var expires = new Date();
				expires.setTime(expires.getTime() + (360 * 24 * 60 * 60 * 1000));
				document.cookie = $opt_cur_form_container.data('cookie_name') + '=' + $opt_cur_form_container.data('cookie') + '; expires=' + expires.toUTCString() + '; path=/; domain=<?php echo $domain ; ?>';
			
				window.setTimeout(function(){
					window.location = opt_redir_url;
				},<?php echo $redirect_time ; ?>*1000);		
			}
			return true;
		}
			
		
		
								
		$form_redirect_link.text('Waiting for opt-in confirmation. Check your email.');
		
		var opt_interval_id;
		
		var check_lead_success = function(CHdata,textStatus,jqXHR){
			if(typeof(CHdata['fail']) !== 'undefined'){return;}
			
			window.clearInterval(opt_interval_id);
			if(typeof(data['optin_no_redirect']) !== 'undefined'){
				opt_ajax_no_redirect(data);
				return true;
			}else if(typeof(data['optin_open_in_new_tab']) !== 'undefined'){
				opt_ajax_new_tab(data);
				return true;
			}else{
				
				$form_waiting.hide();
				$form_success.show();
				
				var expires = new Date();
				expires.setTime(expires.getTime() + (360 * 24 * 60 * 60 * 1000));
				document.cookie = $opt_cur_form_container.data('cookie_name') + '=' + $opt_cur_form_container.data('cookie') + '; expires=' + expires.toUTCString() + '; path=/; domain=<?php echo $domain ; ?>';
			
				window.setTimeout(function(){
					window.location = opt_redir_url;
				},<?php echo $redirect_time ; ?>*1000);		
			}
			
			
		}
		
		opt_interval_id = window.setInterval(function(){
			jQuery.ajax(opt_ajaxurl,{'dataType' : 'json',
								'data': {'action' : 'opt_check_lead',
										'cookie' : $opt_cur_form_container.data('cookie')},
								'success' : check_lead_success});	
		},5*1000);
		return;
	}
	function opt_ajax_options(data){
		
		if(typeof(data['error']) !== 'undefined' ){
			if(data['error'] === 'invalid_email'){
				$form_processing.hide();
				$form_error.show();
				return true;
			}else{
				alert(data['error']);	
				return true;
			}	
		}
		
		
		
		if(typeof(data['double_optin']) !== 'undefined'){
			opt_ajax_double(data);
			return true;
		}else if(typeof(data['optin_no_redirect']) !== 'undefined'){
			opt_ajax_no_redirect(data);
			return true;
		}else if(typeof(data['optin_open_in_new_tab']) !== 'undefined'){
			opt_ajax_new_tab(data);
			return true;
		}
		
		return false;
	}
	
	function opt_form_no_thanks(link_id){
		
		var clicked = $opt_cur_form_container.data('clicked');
		if(typeof(clicked) == 'undefined'){$opt_cur_form_container.data('clicked',true);}else if(clicked){return;}
		
		$form_processing = jQuery('#optin_link_form_processing' + link_id);
		$form_success = jQuery('#optin_link_form_success' + link_id);
		$form_error = jQuery('#optin_link_form_error' + link_id);
		$form = jQuery('#optin_link_form' + link_id);
		$form_success_image = jQuery('#optin_link_success_image' + link_id);
		
		$form_redirect_link = jQuery('#optin_link_redirect_text' + link_id);
		
		$email = jQuery('#optin_link_form_email'+ link_id);
		$name = jQuery('#optin_link_form_name'+ link_id);
		
		if( false ){
			$form_error.show();
		}else{
			$form_error.hide();
			$form_processing.fadeIn();
			window.setInterval(function(){var _this = jQuery('#optin_link_process_dots' + link_id);var num = _this.data('num');if(typeof(num)=='undefined'){num=0;}var dots='';for(var i =0;i<num;i++){dots+='.';}_this.text(dots);var dir = _this.data('dir');if(typeof(dir)=='undefined'){dir=1;}if(num > 3){dir = -1;}if(num < 0){dir = 1;}num += dir; _this.data('num',num); _this.data('dir',dir);},250);
			var data = {'dataType' : 'json',
							'data': {'action' : 'opt_create_lead',
									'visitor_cookie' : dwpc_visitor_id,
									'impression_id' : dwpc_impression_id,
									'forms_id' : $opt_cur_form_container.data('form_id'),
									'links_id' : link_id,
									'link_tracking_id' : $opt_cur_form_container.data('opt_link_tracking_id'),
									'email' : $email.val(),
									'name' : $name.val(),
									'secured_page' : opt_secured_page_id,
									'no_thanks' : 1 },
						'success' : function(data,textStatus,jqXHR){
							$opt_cur_form_container.data('clicked',false);
							if(opt_ajax_options(data)){return;}
							
							$form.hide();
							$form_success.show();
							
							opt_redir_url = data['redir_url'];
							
							opt_set_cookie(data);
							
							
							window.setTimeout(function(){
								window.location = opt_redir_url;
							},<?php echo $redirect_time ; ?>*1000);
						}};
			
			jQuery.ajax(opt_ajaxurl, data);	
			
		}
	}
	function opt_find_value(id){
		if(typeof(id) != 'string'){return '';}
		
		var $obj = jQuery('#'+id);
		if($obj.length == 0){return '';}
		
		return $obj.val();
			
	}
	function opt_element_exists(id){
		if(typeof(id) != 'string'){return false;}
		
		var $obj = jQuery('#'+id);
		if($obj.length == 0){return false;}
		return true;	
	}
	function opt_check_elem(id){
		var find_value = opt_find_value(id)!='';
		var elem_exists = opt_element_exists(id);
		return !elem_exists || (elem_exists && find_value);	
	}
	function opt_rgxemvd(inp){return /[^\s@]+@[^\s@]+\.[^\s@]+/.test(inp);}
	function rawurlencode(str) { str = (str + '').toString();return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/~/g, '%7E');}
    <?php
	if($noscript == ''){
		?>
        </script>
        <?php	
	}
}
function opt_is_camp_fb_en($optinlink_id){
	global $wpdb; 
	$link = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_optin_links WHERE id='.$optinlink_id,ARRAY_A);
	$camp = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_campaigns WHERE id='.$link['opt_campaign_id'],ARRAY_A);	
	if($camp['sendreach_facebook'] == '1'){
		return true;	
	}else{
		return false;	
	}//
}
function opt_get_installed_forms(){
	
	global $wpdb,$dwpc;
	
	$dir =  WP_PLUGIN_DIR . '/opt/optin_forms';
	$files = array();
	$handle = opendir($dir); 
    while (($file = readdir($handle)) !== false) { 
        if ($file == '.' || $file == '..') { 
            continue; 
        } 
        $filepath = $dir == '.' ? $file : $dir . '/' . $file; 
        if (is_link($filepath)) 
            continue; 
        if (is_file($filepath) && strpos(strrev($filepath),'php.') === 0 ) 
            $files[] = $filepath; 
        else if (is_dir($filepath)) 
            continue; 
    } 
    closedir($handle); 
	
	
	$uploads = array();
	foreach($files as $file){
		$handle = fopen($file,'r');
		$line = fgets($handle);
		while( $line !== false)
		{
			if(strpos($line,'//title') !== false){
				$filename = str_replace($dir.'/','',$file);
				$uploads[$filename] = trim( str_replace('//title','',$line) );
				break;	
			}
			$line = fgets($handle);
		}
		fclose($handle);
			
	}
	
	foreach($uploads as $url=>$title){
		$form = $wpdb->get_row('SELECT id FROM '.OPT_DB_PREFIX.'opt_forms WHERE name="'.$title.'"');
		
		if(empty($form)){
			$data = array(
				'time_created'=>current_time('mysql'),
				'file_url'=>$url,
				'name'=>$title,
				'data'=>'',
				'parent_id'=>0
				);	
			$dwpc->insert(OPT_DB_PREFIX.'opt_forms',$data);
		}
	}
	
	$retVal = $wpdb->get_results('SELECT id,name FROM '.OPT_DB_PREFIX.'opt_forms WHERE parent_id=0',ARRAY_A);
	
	return $retVal;
}
//todo: finish - render js or send them to textid
function opt_render_optin_link($optin_link_id, $link_text){
	global $wpdb,$opt_cookie,$dwpc;

	$split_test_item_id = 0;
	
	$html = '<a href="';

	$link = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_optin_links WHERE id='.$optin_link_id,ARRAY_A);
	$secured_page = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_secured_pages WHERE id='.$link['opt_secured_page_id'],ARRAY_A);
	$link['url'] = $secured_page['url'];
			
	
	if(empty($link)){return false;}
	
	if( isset( $_COOKIE[ $opt_cookie[ $link['opt_campaign_id'] ] ] ) && !$link['optin_no_redirect']){
		
		$html .= $link['url'] . '">'.$link_text.'</a>'; 
		
	}else if($link['link_type'] == 'Direct'){
		$url = (strpos($link['url'],'?')!== false)?$link['url'].'&opt='.$link['text_id']: $link['url'].'?opt='.$link['text_id'];
		
		if(array_key_exists('optinlinks_email',$_GET) && $_GET['optinlinks_email'] != ''){
			$url .= '&optinlinks_email='.$_GET['optinlinks_email'];	
		}
		
		if(array_key_exists('optinlinks_name',$_GET) && $_GET['optinlinks_name'] != ''){
			$url .= '&optinlinks_name='.$_GET['optinlinks_name'];	
		}
		$html .= 'javascript:void(0)" onClick="opt_log_link_click('.$optin_link_id.',\''.$url.'\')">'.$link_text.'</a>';
	}else{
		
		$auto_success = false;
		if(isset( $_COOKIE[ $opt_cookie[ $link['opt_campaign_id'] ] ] )){
			$auto_success = true;	
		}
		
		$split_test_item_id = opt_get_form($optin_link_id,$split_test_item_id,0,$auto_success);
		
		$campaign = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_campaigns WHERE id='.$link['opt_campaign_id'],ARRAY_A);
		if($campaign['sendreach_facebook'] == '1'){
			$use_facebook = 'true';	
		}else{
			$use_facebook = 'false';	
		}
		
		$onclick = 'opt_secured_link_click('.$optin_link_id.','.$link['opt_form_id'].','.$split_test_item_id.','.$use_facebook.');';
		
		/*if($link['optin_open_in_new_tab']){
			$url = (strpos($link['url'],'?')!== false)?$link['url'].'&opt='.$link['text_id']: $link['url'].'?opt='.$link['text_id'];
			$onclick = 	'opt_form_success=0;'.$onclick.'opt_int_id = window.setInterval(function(){if(opt_form_success==1){window.open(\''.$url.'\',\'_blank\');window.clearInterval(opt_int_id);}},500);';
		}*/
		
		$html .= 'javascript:void(0);" onClick="'.$onclick.'"';
		$html .= '>'.$link_text.'</a>';
	}
	
	global $optin_link_loads;
	global $opt_has_rendered_form_js;
	//some fucker isnt running wp_head
	if(empty($opt_has_rendered_form_js) || !$opt_has_rendered_form_js){
		opt_set_js_variables();
		opt_form_tracking();
	}
	
	if(!is_array($optin_link_loads)){
		$optin_link_loads = array($optin_link_id);
		$dwpc->insert(OPT_DB_PREFIX.'opt_optin_link_tracking',array('time_created'=>current_time('mysql'),
				'tracking_type'=>'Load',
				'dwpc_visitor_id'=>$dwpc->visitor['id'],
				'dwpc_impression_id'=>$dwpc->impression['id'],
				'opt_optin_link_id'=>$optin_link_id));	
	}else{
		if(	!in_array($optin_link_id,$optin_link_loads) ){	
			$opt_forms_rendered[] = $optin_link_id;				
			$dwpc->insert(OPT_DB_PREFIX.'opt_optin_link_tracking',array('time_created'=>current_time('mysql'),
				'tracking_type'=>'Load',
				'dwpc_visitor_id'=>$dwpc->visitor['id'],
				'dwpc_impression_id'=>$dwpc->impression['id'],
				'opt_optin_link_id'=>$optin_link_id));
		}
	}
	
	
	return $html;
}

//[OptinLink id=x][/OptinLink]
function optin_link_shortcode($attrs,$content){
	$attrs = shortcode_atts(array('id'=>0),$attrs,'OptinLink');
		
	return opt_render_optin_link($attrs['id'],do_shortcode($content));
}



function opt_button_generator($button_type='gradient',$link_type='submit',$color='#0000ff',$border_radius=3,$opt_link_id='',$button_text='',$style='', $url='') {
	
	if($url != ''){
		return '<img src="'.$url.'"/>';	
	}
	
	if($opt_link_id=='') {
		
		$opt_link_id = opt_random_string(5,10);	
		
	}
	
	$hsl = opt_hex_to_hsl($color);	
	
	if($button_type=='flat') { 		
	
	$output = '
		
        <style type="text/css">  
		
			.optin_link_button'.intval($opt_link_id).' {
			  
			  display:inline-block;
			  vertical-align:middle !important;
				
			  padding: 10px 32px !important;
			  border: 0 !important;
			  margin: 0 !important;
			  line-height:1.5 !important;
			  font-size: 15px !important;
			  text-decoration:none !important;
			  color: white !important;
			  text-align: center !important;
			  background: '.$color.';
			  cursor: pointer !important;
			  -webkit-border-radius: '.$border_radius.'px !important;
			  -moz-border-radius: '.$border_radius.'px !important;
			  border-radius: '.$border_radius.'px !important;
			  
			}	
			
            .optin_link_button'.intval($opt_link_id).':hover {
                
			  opacity:0.9 !important;
			  filter:Alpha(opacity=90) !important;
			  cursor:pointer !important;
              color: #ffffff !important;
				  
            }
		
		</style>
        
	';
	
	} elseif($button_type=='3d') { 
	
	$color2 = opt_hsl_to_hex(intval($hsl['Hue']),intval($hsl['Saturation']*1.1),intval($hsl['Luminance']*0.7));
	
	$output = '
        
        <style type="text/css">  
		
			.optin_link_button'.intval($opt_link_id).' {
			  
			  display:inline-block;
			  vertical-align:middle !important;
			  
			  padding: 9px 32px !important;
			  border: 0 !important;
			  margin: 0 !important;
			  line-height:1.5 !important;
			  font-size: 15px !important;
			  text-decoration:none !important;
			  color: white !important;
			  text-align: center !important;
			  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25) !important;
			  background: '.$color.';
			  border-bottom: 2px solid '.$color2.';
			  cursor: pointer !important;
			  -webkit-box-shadow: inset 0 -2px '.$color2.';
			  box-shadow: inset 0 -2px '.$color2.';
			  -webkit-border-radius: '.$border_radius.'px !important;
			  -moz-border-radius: '.$border_radius.'px !important;
			  border-radius: '.$border_radius.'px !important;
			  
			}			
			
			.optin_link_button'.intval($opt_link_id).':active {
				
			  top: 1px !important;
			  outline: none !important;
			  -webkit-box-shadow: none !important;
			  box-shadow: none !important;
			  
			}
			
            .optin_link_button'.intval($opt_link_id).':hover {
                
                opacity:0.9 !important;
                filter:Alpha(opacity=90) !important;
                cursor:pointer !important;
                color: #ffffff !important;
                    
            }

		</style>
		
		';
	
	} elseif($button_type=='gradient') { 	
	
	$color2 = opt_hsl_to_hex(intval($hsl['Hue']),intval($hsl['Saturation']*1.1),intval($hsl['Luminance']*0.85));
	$color3 = opt_hsl_to_hex(intval($hsl['Hue']),intval($hsl['Saturation']*1.2),intval($hsl['Luminance']*0.55));
	
	$output = '
        
        <style type="text/css">        
        
            .optin_link_button'.intval($opt_link_id).', .optin_link_button'.intval($opt_link_id).':link{
                
				display:inline-block;
				vertical-align:middle !important; 
				
                background-color: '.$color.';
                background-image: -moz-linear-gradient(top, '.$color.', '.$color2.');
                background-image: -ms-linear-gradient(top, '.$color.', '.$color2.');
                background-image: -webkit-gradient(linear, '.$color.', '.$color2.');
                background-image: -webkit-linear-gradient(top, '.$color.', '.$color2.');
                background-image: -o-linear-gradient(top, '.$color.', '.$color2.');
                background-image: linear-gradient(top, '.$color.', '.$color2.');
                background-repeat: repeat-x !important;
                
                filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="'.$color.'", endColorstr="'.$color2.'", GradientType=0);
                
                border-color: '.$color2.' '.$color2.' '.$color3.';
                border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25) !important;
                font-family: "Droid Sans","Open Sans",Arial !important;	
                    
                text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25) !important;
                text-decoration: none !important;
                color: #ffffff !important;
                font-size: 15px !important;
                font-weight: normal !important;
                line-height: 1.5 !important;
				
				margin:0 !important;
                -webkit-border-radius: '.$border_radius.'px !important;
                -moz-border-radius: '.$border_radius.'px !important;
                border-radius: '.$border_radius.'px !important;
                				
                box-shadow: 0px 1px 0px rgba(255, 255, 255, 0.2) inset, 0px 1px 2px rgba(0, 0, 0, 0.05) !important;
                padding: 9px 32px !important;
                border-width: 1px !important;
                border-style: solid !important;
                -moz-border-top-colors: none !important;
                -moz-border-right-colors: none !important;
                -moz-border-bottom-colors: none !important;
                -moz-border-left-colors: none !important;
                border-image: none !important;
                border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25) !important;
				                
                
            }
            
            .optin_link_button'.intval($opt_link_id).':hover {
                
                opacity:0.9 !important;
                filter:Alpha(opacity=90) !important;
                cursor:pointer !important;
                color: #ffffff !important;
                    
            }
			
		</style>     
        
        ';
		
	}


if($link_type=='submit') {

    $output .= '<a href="javascript:void(0)" onClick="opt_form_submit('.intval($opt_link_id).');" class="optin_link_button'.intval($opt_link_id).'" id="optin_link_button_text'.intval($opt_link_id).'" '.$style.'>'.$button_text.'</a>';
	
} elseif($link_type=='optinlink') {
	
	$output .= '<span class="optin_link_button'.intval($opt_link_id).'" '.$style.'>'.$button_text.'</span>';
	
}

return  $output;

	
}


function opt_hex_to_hsl( $HexColor )
{

        $HexColor    = str_replace( '#', '', $HexColor );

        if( strlen( $HexColor ) < 3 ) str_pad( $HexColor, 3 - strlen( $HexColor ), '0' );

        $Add         = strlen( $HexColor ) == 6 ? 2 : 1;
        $AA          = 0;
        $AddOn       = $Add == 1 ? ( $AA = 16 - 1 ) + 1 : 1;

        $Red         = round( ( hexdec( substr( $HexColor, 0, $Add ) ) * $AddOn + $AA ) / 255, 6 );
        $Green       = round( ( hexdec( substr( $HexColor, $Add, $Add ) ) * $AddOn + $AA ) / 255, 6 );
        $Blue        = round( ( hexdec( substr( $HexColor, ( $Add + $Add ) , $Add ) ) * $AddOn + $AA ) / 255, 6 );


        $HSLColor    = array( 'Hue' => 0, 'Saturation' => 0, 'Luminance' => 0 );

        $Minimum     = min( $Red, $Green, $Blue );
        $Maximum     = max( $Red, $Green, $Blue );

        $Chroma      = $Maximum - $Minimum;


        $HSLColor['Luminance'] = ( $Minimum + $Maximum ) / 2;

        if( $Chroma == 0 )
        {
                $HSLColor['Luminance'] = round( $HSLColor['Luminance'] * 255, 0 );

                return $HSLColor;
        }


        $Range = $Chroma * 6;


        $HSLColor['Saturation'] = $HSLColor['Luminance'] <= 0.5 ? $Chroma / ( $HSLColor['Luminance'] * 2 ) : $Chroma / ( 2 - ( $HSLColor['Luminance'] * 2 ) );

        if( $Red <= 0.004 || $Green <= 0.004 || $Blue <= 0.004 )
                $HSLColor['Saturation'] = 1;


        if( $Maximum == $Red )
        {
                $HSLColor['Hue'] = round( ( $Blue > $Green ? 1 - ( abs( $Green - $Blue ) / $Range ) : ( $Green - $Blue ) / $Range ) * 255, 0 );
        }
        else if( $Maximum == $Green )
        {
                $HSLColor['Hue'] = round( ( $Red > $Blue ? abs( 1 - ( 4 / 3 ) + ( abs ( $Blue - $Red ) / $Range ) ) : ( 1 / 3 ) + ( $Blue - $Red ) / $Range ) * 255, 0 );
        }
        else
        {
                $HSLColor['Hue'] = round( ( $Green < $Red ? 1 - 2 / 3 + abs( $Red - $Green ) / $Range : 2 / 3 + ( $Red - $Green ) / $Range ) * 255, 0 );
        }




        $HSLColor['Saturation'] = round( $HSLColor['Saturation'] * 255, 0 );
        $HSLColor['Luminance']  = round( $HSLColor['Luminance'] * 255, 0 );



        return $HSLColor;


}

function opt_hsl_to_hex( $Hue = 0, $Saturation = 0, $Luminance = 0 )
{

		if($Saturation>255) { $Saturation = 255; }
		if($Luminance>255) { $Luminance = 255; }
	
        $HSLColor    = array( 'Hue' => $Hue, 'Saturation' => $Saturation, 'Luminance' => $Luminance );
        $RGBColor    = array( 'Red' => 0, 'Green' => 0, 'Blue' => 0 );


        foreach( $HSLColor as $Name => $Value )
        {
                if( is_string( $Value ) && strpos( $Value, '%' ) !== false )
                        $Value = round( round( (int)str_replace( '%', '', $Value ) / 100, 2 ) * 255, 0 );

                else if( is_float( $Value ) )
                        $Value = round( $Value * 255, 0 );

                $Value    = (int)$Value * 1;
                $Value    = $Value > 255 ? 255 : ( $Value < 0 ? 0 : $Value );
                $ValuePct = round( $Value / 255, 6 );

                $hsl_arr[$Name] = $ValuePct;

        }

        $RGBColor['Red']   = $hsl_arr['Luminance'];
        $RGBColor['Green'] = $hsl_arr['Luminance'];
        $RGBColor['Blue']  = $hsl_arr['Luminance'];
		
        $Radial  = $hsl_arr['Luminance'] <= 0.5 ? $hsl_arr['Luminance'] * ( 1.0 + $hsl_arr['Saturation'] ) : $hsl_arr['Luminance'] + $hsl_arr['Saturation'] - ( $hsl_arr['Luminance'] * $hsl_arr['Saturation'] );

        if( $Radial > 0 )
        {

                $Ma   = $hsl_arr['Luminance'] + ( $hsl_arr['Luminance'] - $Radial );
                $Sv   = round( ( $Radial - $Ma ) / $Radial, 6 );
                $Th   = $hsl_arr['Hue'] * 6;
                $Wg   = floor( $Th );
                $Fr   = $Th - $Wg;
                $Vs   = $Radial * $Sv * $Fr;
                $Mb   = $Ma + $Vs;
                $Mc   = $Radial - $Vs;


                // Color is between yellow and green
                if ($Wg == 1)
                {
                        $RGBColor['Red']   = $Mc;
                        $RGBColor['Green'] = $Radial;
                        $RGBColor['Blue']  = $Ma;
                }
                // Color is between green and cyan
                else if( $Wg == 2 )
                {
                        $RGBColor['Red']   = $Ma;
                        $RGBColor['Green'] = $Radial;
                        $RGBColor['Blue']  = $Mb;
                }

                // Color is between cyan and blue
                else if( $Wg == 3 )
                {
                        $RGBColor['Red']   = $Ma;
                        $RGBColor['Green'] = $Mc;
                        $RGBColor['Blue']  = $Radial;
                }

                // Color is between blue and magenta
                else if( $Wg == 4 )
                {
                        $RGBColor['Red']   = $Mb;
                        $RGBColor['Green'] = $Ma;
                        $RGBColor['Blue']  = $Radial;
                }

                // Color is between magenta and red
                else if( $Wg == 5 )
                {
                        $RGBColor['Red']   = $Radial;
                        $RGBColor['Green'] = $Ma;
                        $RGBColor['Blue']  = $Mc;
                }

                // Color is between red and yellow or is black
                else
                {
                        $RGBColor['Red']   = $Radial;
                        $RGBColor['Green'] = $Mb;
                        $RGBColor['Blue']  = $Ma;
                }

         }



         $RGBColor['Red']   = ($C = round( $RGBColor['Red'] * 255, 0 )) < 15 ? '0'.dechex( $C ) : dechex( $C );
         $RGBColor['Green'] = ($C = round( $RGBColor['Green'] * 255, 0 )) < 15 ? '0'.dechex( $C ) : dechex( $C );
         $RGBColor['Blue']  = ($C = round( $RGBColor['Blue'] * 255, 0 )) < 15 ? '0'.dechex( $C ) : dechex( $C );



         return '#' . $RGBColor['Red'].$RGBColor['Green'].$RGBColor['Blue'];


}

function opt_poweredby() {
	
	
	
	$show_it = opt_settings('show_powered_by');
	$affiliate_link = opt_settings('optinlinks_affiliate_link');
	
	if($show_it=='') { $show_it = 1; opt_settings('show_powered_by',1); }
	if($affiliate_link=='') { $affiliate_link = 'http://www.optinlinks.com'; opt_settings('optinlinks_affiliate_link',$affiliate_link);}

	if($show_it==1) {

	$output = '
	
		<div style="position:absolute; right:15px; bottom:15px; top:auto; left: auto; border:1px solid #333; background:#222; padding:3px 8px; border-radius:5px;">
		
			<a target="_blank" href="'.$affiliate_link.'" style="color:#777; text-decoration:none; font-family:\'Open Sans\', Arial; font-size:12px; line-height:12px; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);"><span style="font-size:10px;">Powered by</span> <span style="color:#fff; font-weight:bold; margin-left:3px;">OPTINLINKS</span></a>		
		
		</div>
	
	
	';	
	
	return $output;
	
	}
	
}

?>