<?php
require_once dirname(__FILE__) . '../../../../../wp-config.php';
require_once dirname(__FILE__) . '../../opt.php';

header('Access-Control-Allow-Origin: *');
header("Content-type: application/javascript");

echo '/*
OptinLinks Shortcode Helper
OptinLinks is © 2014 StrongMRKTG LLC
*/';
$linkTable = OPT_DB_PREFIX.'opt_optin_links';
$campTable = OPT_DB_PREFIX.'opt_campaigns';
$spTable = OPT_DB_PREFIX.'opt_secured_pages';
$formTable = OPT_DB_PREFIX.'opt_forms';
$stTable = OPT_DB_PREFIX.'opt_split_tests';
$query = '

SELECT 
'.$linkTable.'.id, 
'.$campTable.'.name as campaign_name, 
'.$linkTable.'.name as name, 
'.$spTable.'.name as secured_page_name, 
'.$spTable.'.url as secured_page_url, 
'.$linkTable.'.opt_form_id as opt_form_id,
'.$linkTable.'.opt_split_test_id as opt_split_test_id

FROM '.$linkTable.' 

JOIN '.$campTable.' ON '.$linkTable.'.opt_campaign_id = '.$campTable.'.id 
JOIN '.$spTable.' ON '.$linkTable.'.opt_secured_page_id = '.$spTable.'.id 

WHERE '.$linkTable.'.deleted != 1 
AND '.$campTable.'.deleted != 1 

ORDER BY campaign_name ASC, '.$linkTable.'.name';

$links = $wpdb->get_results($query,ARRAY_A);


foreach($links as $key=>$value){

	if($value['opt_form_id'] != 0){
		$links[$key]['form_name'] = $wpdb->get_var('SELECT name FROM '.$formTable.' WHERE id='.$value['opt_form_id']);
	}elseif($value['opt_split_test_id'] != 0 ){
		$links[$key]['form_name'] = 'Split Test:'.$wpdb->get_var('SELECT name FROM '.$stTable.' WHERE id='.$value['opt_split_test_id']);
	}
}


$images_href = plugins_url('/opt/optin_forms/images/');

/*sidenotes: this is builder compatible AS LONG AS we keep the JS comments in the /* style 

check out http://codingdroid.com/adding-custom-button-wordpress-tinymce-editor/
and scroll to the bottom of the post to see how we could potentially make this visual mode friendly
not sure it'll work too well with shortcodes, but we could maybe hax in some kind of <span> around the sc that had no functionality 
front end....idk that'll work but is probably a bad idea. Food for thought. 

*/

?>
/*<script>*/
function ltrim(str,c){
	while(str.charAt(0) === c){
		str = str.substr(1);	
	}
	return str;
}
function opt_componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}

function opt_rgbToHex(r, g, b) {
    return "#" + opt_componentToHex(r) + opt_componentToHex(g) + opt_componentToHex(b);
}
function opt_hexToRgb(hex) {
    var bigint = parseInt( ltrim(hex,'#') , 16);
    return { r : (bigint >> 16) & 255, g : (bigint >> 8) & 255, b : bigint & 255}
}
/**
 * Converts an RGB color value to HSL. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
 * Assumes r, g, and b are contained in the set [0, 255] and
 * returns h, s, and l in the set [0, 1].
 *
 * @param   Number  r       The red color value
 * @param   Number  g       The green color value
 * @param   Number  b       The blue color value
 * @return  Array           The HSL representation
 */
function opt_rgbToHsl(r, g, b){
    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b), min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min){
        h = s = 0; // achromatic
    }else{
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max){
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    return {h:h, s:s, l:l};
}
function clamp(min,max,x){
	return Math.min(Math.max(x,min),max);
}
/**
 * Converts an HSL color value to RGB. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
 * Assumes h, s, and l are contained in the set [0, 1] and
 * returns r, g, and b in the set [0, 255].
 *
 * @param   Number  h       The hue
 * @param   Number  s       The saturation
 * @param   Number  l       The lightness
 * @return  Array           The RGB representation
 */
function opt_hslToRgb(h, s, l){
    var r, g, b;

    if(s == 0){
        r = g = b = l; // achromatic
    }else{
        function hue2rgb(p, q, t){
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return {r:clamp(0,255,Math.round(r * 255)), g: clamp(0,255,Math.round(g * 255)), b: clamp(0,255,Math.round(b * 255))};
}
(function() {
	var optin_links = <?php echo json_encode($links); ?>;
    var curEd;
    
    var $overlay = jQuery('<div style="position:fixed; top:0; left:0; width:100%; height:100%; opacity:0.7; filter:Alpha(opacity=70); z-index:1000000; background-color:#000; display:none;"></div>').appendTo('body');
	
	var $form_container = jQuery('<div style="position:fixed; top:18%; left:14%; right:14%; z-index:1000001; display:none;"></div>').appendTo('body');
	
   
    
    
	var $link_container = jQuery('<div style="margin-left:auto; margin-right:auto; width:80%; border:1px solid #ddd; z-index:1000002; background-color:#fff; opacity:1.0; filter:Alpha(opacity=100); "></div>').appendTo($form_container);
   	
    
    
    var $header_container = jQuery('<h3 style="padding:10px; margin-top:0" class="opt_form_h3">OptinLinks Shortcode Generator<a href="javascript:void(0)" id="optin_form_close_button" class="button" style="float:right; margin-top:-5px;">Close</a></h3>').appendTo($link_container);
	
    
	jQuery('#optin_form_close_button').click(function(){
		$overlay.fadeOut();	
		$form_container.fadeOut();	
	});
	
	$overlay.click(function(){
		$overlay.fadeOut();	
		$form_container.fadeOut();
	});
	
  
    
    var $append_the_link_elements_to_this =  jQuery('<div style="padding:20px; padding-top:0; height:400px; overflow-y:scroll;"></div>').appendTo($link_container); 
    

    var use_button = false;
    var button_text = '';
    var color = '#aabbff';
    var button_type = 'gradient';
    
    if(button_text == ''){
    	button_text = 'OptinLink Button Text';
    }
    
    var $button_generator_title = jQuery('<div><span style="margin-top:0;" class="button-primary">Create Custom OptinLink Button</span></div>').appendTo($append_the_link_elements_to_this);
    var $button_cancel = jQuery('<a href="javascript:void(0)" id="optin_form_close_button" class="button" style="float:right; display:none; z-index:1000000000;">Cancel</a>').appendTo($button_generator_title);
    
    $button_cancel.click(function(event){
    	use_button = false;
        $button_generator_body.slideUp();
        $button_cancel.fadeOut();
        event.stopPropagation();
    });
    
    var $button_generator_body = jQuery('<div style="display:none; background-color:#f3f3f3; padding:10px; margin-top:10px;"></div>').appendTo($append_the_link_elements_to_this);
    
    
    var $button_text = jQuery('<input type="textarea" style="width:100%; margin-top:10px; margin-bottom:10px;" />').appendTo($button_generator_body);
    
    jQuery('<br />').appendTo($button_generator_body);    
    
    var $color_picker = jQuery('<input type="text" name="button_color" id="color_1" data-default-color="#0088cc" value="#0088cc" style="width:80px;" />').appendTo($button_generator_body);         
                    
    var $button_border_radius = jQuery('<input type="number" value="3" min=0 max=100 style="width:50px; position:relative;" />').prependTo(jQuery('<span style=" position:relative; top:-10px;">px Border Radius</span>').appendTo($button_generator_body));
    
    jQuery('<br />').appendTo($button_generator_body);
    
    var $gradient_button = jQuery('<?php echo str_replace(chr(10),'',str_replace(chr(13),'',preg_replace('/^\s+|||\s+$/m','',opt_button_generator('gradient','optinlink','#0088cc',3,1,'Gradient')))) ; ?>').appendTo(jQuery('<span></span>').appendTo($button_generator_body));
    var $flat_button = jQuery('<?php echo str_replace(chr(10),'',str_replace(chr(13),'',preg_replace('/^\s+|||\s+$/m','',opt_button_generator('flat','optinlink','#0088cc',3,2,'Flat')))) ; ?>').appendTo(jQuery('<span style="margin-left:10px;"></span>').appendTo($button_generator_body));
    var $3d_button = jQuery('<?php echo str_replace(chr(10),'',str_replace(chr(13),'',preg_replace('/^\s+|||\s+$/m','',opt_button_generator('3d','optinlink','#0088cc',3,3,'3D')))) ; ?>').appendTo(jQuery('<span style="margin-left:10px;"></span><br /><br />').appendTo($button_generator_body));
	
    
    
    jQuery('<div style="background-color:#fffff3; padding:10px; margin-top:-10px; margin-bottom:10px;">Live Button Preview</div>').appendTo($button_generator_body );
    
    
    var $prev_gradient_button = jQuery('<?php echo str_replace(chr(10),'',str_replace(chr(13),'',preg_replace('/^\s+|||\s+$/m','',opt_button_generator('gradient','optinlink','#0088cc',3,1,'Gradient')))) ; ?>').appendTo($button_generator_body);
    var $prev_flat_button = jQuery('<?php echo str_replace(chr(10),'',str_replace(chr(13),'',preg_replace('/^\s+|||\s+$/m','',opt_button_generator('flat','optinlink','#0088cc',3,2,'Flat')))) ; ?>').appendTo($button_generator_body);
    var $prev_3d_button = jQuery('<?php echo str_replace(chr(10),'',str_replace(chr(13),'',preg_replace('/^\s+|||\s+$/m','',opt_button_generator('3d','optinlink','#0088cc',3,3,'3D')))) ; ?>').appendTo($button_generator_body);
	
    $prev_flat_button.hide();
    $prev_3d_button.hide();
    
    $button_border_radius.change(function(){
    	var val = $button_border_radius.val();
        
        $flat_button.css('-webkit-border-radius',val+'px');
        $flat_button.css('-moz-border-radius',val+'px');
        $flat_button.css('border-radius',val+'px');
        $prev_flat_button.css('-webkit-border-radius',val+'px');
        $prev_flat_button.css('-moz-border-radius',val+'px');
        $prev_flat_button.css('border-radius',val+'px');
        
        $gradient_button.css('-webkit-border-radius',val+'px');
        $gradient_button.css('-moz-border-radius',val+'px');
        $gradient_button.css('border-radius',val+'px');
        $prev_gradient_button.css('-webkit-border-radius',val+'px');
        $prev_gradient_button.css('-moz-border-radius',val+'px');
        $prev_gradient_button.css('border-radius',val+'px');
        
        $3d_button.css('-webkit-border-radius',val+'px');
        $3d_button.css('-moz-border-radius',val+'px');
        $3d_button.css('border-radius',val+'px');
        $prev_3d_button.css('-webkit-border-radius',val+'px');
        $prev_3d_button.css('-moz-border-radius',val+'px');
        $prev_3d_button.css('border-radius',val+'px');
    });
    
    $button_text.keyup(function(){
    	button_text = $button_text.val();
        
        $prev_gradient_button.text(button_text);
        $prev_flat_button.text(button_text);
        $prev_3d_button.text(button_text);
    });
    
    $button_text.keydown(function(){
    	button_text = $button_text.val();
        
        $prev_gradient_button.text(button_text);
        $prev_flat_button.text(button_text);
        $prev_3d_button.text(button_text);
    });
    
    $gradient_button.click(function(){
    	$prev_flat_button.hide();
        $prev_3d_button.hide();
        $prev_gradient_button.show();
        
        button_type = 'gradient';
    });
    
    $flat_button.click(function(){
    	
        $prev_3d_button.hide();
        $prev_gradient_button.hide();
        $prev_flat_button.show();
        button_type = 'flat';
    });
    
    $3d_button.click(function(){
    	$prev_flat_button.hide();
        
        $prev_gradient_button.hide();
        $prev_3d_button.show();
        button_type = '3d';
    });
    
    var setColors = function(hex){
		
    	color = hex;
    	var main_color = opt_hexToRgb(hex);
        var main_hsl = opt_rgbToHsl(main_color.r,main_color.g,main_color.b);
        
        /*flat*/
        $flat_button.css('background',hex);
        $prev_flat_button.css('background',hex);
        
        /*gradient*/
        var color2_rgb = opt_hslToRgb(main_hsl.h,main_hsl.s*1.1,main_hsl.l*0.85);
        var color2_hex = opt_rgbToHex(color2_rgb.r,color2_rgb.g,color2_rgb.b);
        
        var color3_rgb = opt_hslToRgb(main_hsl.h,main_hsl.s*1.2,main_hsl.l*0.55);
        var color3_hex = opt_rgbToHex(color2_rgb.r,color2_rgb.g,color2_rgb.b);
        
        

   		var grad_extras = '';
        if(button_type != 'gradient'){
        	grad_extras = 'display:none;';
        }
        $gradient_button.attr('style','background-image : -moz-linear-gradient(top, '+hex+', '+color2_hex+');background-image : -ms-linear-gradient(top, '+hex+', '+color2_hex+');background-image : -webkit-gradient(linear, '+hex+', '+color2_hex+');background-image : -webkit-linear-gradient(top, '+hex+', '+color2_hex+');background-image : -o-linear-gradient(top, '+hex+', '+color2_hex+');background-image : linear-gradient(top, '+hex+', '+color2_hex+');filter : progid:DXImageTransform.Microsoft.gradient(startColorstr="'+hex+'", endColorstr="'+color2_hex+'", GradientType=0);border-color : +'+hex + ' ' + color2_hex + ' ' + color3_hex+';background-color : '+hex);
        $prev_gradient_button.attr('style','background-image : -moz-linear-gradient(top, '+hex+', '+color2_hex+');background-image : -ms-linear-gradient(top, '+hex+', '+color2_hex+');background-image : -webkit-gradient(linear, '+hex+', '+color2_hex+');background-image : -webkit-linear-gradient(top, '+hex+', '+color2_hex+');background-image : -o-linear-gradient(top, '+hex+', '+color2_hex+');background-image : linear-gradient(top, '+hex+', '+color2_hex+');filter : progid:DXImageTransform.Microsoft.gradient(startColorstr="'+hex+'", endColorstr="'+color2_hex+'", GradientType=0);border-color : +'+hex + ' ' + color2_hex + ' ' + color3_hex+';background-color : '+hex+';'+grad_extras);

        
      
        /*3d*/
        var color4_rgb = opt_hslToRgb(main_hsl.h,main_hsl.s*1.1,main_hsl.l*0.7);
        var color4_hex = opt_rgbToHex(color2_rgb.r,color2_rgb.g,color2_rgb.b);
        
        $3d_button.css('background',hex);
		$3d_button.css('border-bottom-color',color4_hex);
		$3d_button.css('-webkit-box-shadow','inset 0 -2px '+color4_hex);
        $3d_button.css('box-shadow','inset 0 -2px '+color4_hex);
        
        $prev_3d_button.css('background',hex);
		$prev_3d_button.css('border-bottom-color',color4_hex);
		$prev_3d_button.css('-webkit-box-shadow','inset 0 -2px '+color4_hex);
        $prev_3d_button.css('box-shadow','inset 0 -2px '+color4_hex);
            
    };
    
    $color_picker.wpColorPicker({
			hide : true,
			width : 500,
			palettes: ['#dd3d36','#ffaa00','#64bb38','#34ada5','#0088cc','#7d3ac4','#ce40bd'], /*Make these better*/
			change : function(event,ui){
				
				setColors(ui.color.toString());
				
			}
		});
    
    $button_generator_title.click(function(){
    	$button_generator_body.slideDown();
        use_button = true;
        $button_cancel.fadeIn();
    });
    
    
    
	var campaign_name = '';	
	var row_class_i = 0;
	var campaign_name_border_top = '';
	
    jQuery.each(optin_links,function(index,value){
    	
      
    	var $curContainer = jQuery('<div></div>').appendTo( $append_the_link_elements_to_this );
		 
		 
		 if(campaign_name!=value.campaign_name) {
			 
			 if(row_class_i > 0) { campaign_name_border_top = 'border-top:1px solid #ddd;'; }
			 
        	 jQuery('<div style="font-weight:bold; font-size:16px; padding:25px 0 15px 0; border-bottom:1px solid #ddd; '+campaign_name_border_top+' ">'+value.campaign_name+'<span style="float:right; font-size:14px; font-weight:normal;">Click an OptinLink to insert its shortcode</span></div>').appendTo($curContainer); 
			 
			 campaign_name = value.campaign_name;			 
		 }
		 
		 if(row_class_i%2==1) {row_class = "opt_sub_table_row"; } else { row_class = "opt_sub_table_row_alt"; }	
		 row_class_i++;	
		 html = '';
		 html += '<div class="'+row_class+'" style="padding:5px; padding-left:20px; cursor:pointer;" onmouseover="jQuery(\'#optin_link_'+value.id+'\').show()" onmouseout="jQuery(\'#optin_link_'+value.id+'\').hide()">';
		 html += '<a href="javascript:void(0)">';
		 html += value.name;
		 html += '</a>';
		 html += '<div id="optin_link_'+value.id+'" style="display:none;">';
		 html += 'Secure Page: <strong>'+value.secured_page_name + '</strong>';
		 html += '<span style="margin-left:20px;">Optin Form: <strong>'+value.form_name+'</strong></span>';
		 html += '<div style="color:#999;">'+value.secured_page_url+'</div>';
		 html +='</div>';
		 html += '</div>';
		 
		
        jQuery(html).appendTo($curContainer);       	
    	
		
        $curContainer.data('link_id',value.id);
        $curContainer.click(function(){
        	
			var selected_text = curEd.selection.getContent({format:'html'});
          
			var cur_link_id = jQuery(this).data('link_id');
            if(use_button){
            	selected_text = '[OptinLinkButton button_type='+button_type+' link_type=optinlink color='+color+' border_radius='+$button_border_radius.val()+' button_text="'+button_text+'"]'; 
            }
            
			if(selected_text === ''){
				selected_text = 'Link text goes here.';	
			}
			
        	
			var shortcode = '[OptinLink id=' + cur_link_id + '] '+selected_text+' [/OptinLink]';
            tinyMCE.activeEditor.execCommand('mceInsertContent', 0, shortcode);
            
			$overlay.fadeOut();	
			$form_container.fadeOut();
        });
		
		
		
	
    });
	
	
    jQuery('<div style="padding:0; border-top:1px solid #ddd;"></div>').appendTo( $append_the_link_elements_to_this); 
			 
    
	tinymce.create('tinymce.plugins.OptinLinksShortcodeHelper', {
		init : function(ed, url) {
			ed.addButton('OptinLinksShortcodeHelper', {
				title : 'OptinLinksShortcodeHelper',
				image : url+'/button.png',
				cmd: 'opt_optin_link_shortcode_command'
			});
			ed.addCommand('opt_optin_link_shortcode_command',function(){
                

                curEd = ed;
                
                button_text = curEd.selection.getContent({format:'html'});
                
                if(button_text == ''){
                	button_text = 'OptinLink Button Text';
                }
                
                $prev_gradient_button.text(button_text);
                $prev_flat_button.text(button_text);
                $prev_3d_button.text(button_text);
                
                $button_text.val(button_text);
    
				$overlay.fadeIn();
				$form_container.fadeIn();
                
            });
		},
		getInfo : function() {
			return {
				longname : "OptinLinks Shortcode Helper",
				author : 'Dylan Ross & Donald Westendorp',
				authorurl : 'http://www.optinlinks.com/',
				infourl : 'http://www.optinlinks.com/',
				version : "1.0"
			};
		}
	});
	tinymce.PluginManager.add('OptinLinksShortcodeHelper', tinymce.plugins.OptinLinksShortcodeHelper);
})();
<?php
$closing_statement = "Why have you read this far?";

?>