<?php

if ( function_exists('register_sidebar') )
    register_sidebars(4,array(
        'before_widget' => '<div class="widgettop"></div><div class="widget"><div class="widgetinside">',
        'after_widget' => '</div><!-- close widgetinside--></div><!-- close widget--><div class="widgetbottom"></div>',
        'before_title' => '<h2>',
        'after_title' => '</h2>',
    ));



	function LimitText($Text,$Min,$Max,$MinAddChar)
	{
	    if (strlen($Text) < $Min)
	    {
	        $Limit = $Min-strlen($Text);
	        $Text .= $MinAddChar;
	    }
	    elseif (strlen($Text) >= $Max)
	    {
	        $words = explode(" ", $Text);
	        $check=1;
	        while (strlen($Text) >= $Max)
	        {
	            $c=count($words)-$check;
	            $Text=substr($Text,0,(strlen($words[$c])+1)*(-1));
	            $check++;
	        }
	    }

	    return $Text;
}

function bdw_get_images($postID,$imgwidth,$imgheight)
{

    // Get the post ID
    $iPostID = $postID;

    // Get images for this post
    $arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );

    // If images exist for this page
    if($arrImages)
    {

        // Get array keys representing attached image numbers
        $arrKeys = array_keys($arrImages);

		/******BEGIN BUBBLE SORT BY MENU ORDER************
		// Put all image objects into new array with standard numeric keys (new array only needed while we sort the keys)
		foreach($arrImages as $oImage)
		{
			$arrNewImages[] = $oImage;
		}

		// Bubble sort image object array by menu_order TODO: Turn this into std "sort-by" function in functions.php
		for($i = 0; $i < sizeof($arrNewImages) - 1; $i++)
		{
			for($j = 0; $j < sizeof($arrNewImages) - 1; $j++)
			{
				if((int)$arrNewImages[$j]->menu_order > (int)$arrNewImages[$j + 1]->menu_order)
				{
					$oTemp = $arrNewImages[$j];
					$arrNewImages[$j] = $arrNewImages[$j + 1];
					$arrNewImages[$j + 1] = $oTemp;
				}
			}
		}

		// Reset arrKeys array
		$arrKeys = array();

		// Replace arrKeys with newly sorted object ids
		foreach($arrNewImages as $oNewImage)
		{
			$arrKeys[] = $oNewImage->ID;
		}
		******END BUBBLE SORT BY MENU ORDER**************/

        // Get the first image attachment
        $iNum = $arrKeys[0];

        // Get the thumbnail url for the attachment
        $sThumbUrl = wp_get_attachment_thumb_url($iNum);

        // UNCOMMENT THIS IF YOU WANT THE FULL SIZE IMAGE INSTEAD OF THE THUMBNAIL
        //$sImageUrl = wp_get_attachment_url($iNum);

        // Build the <img> string
        $sImgString = '<a href="' . get_permalink() . '">' .
                            '<img src="' . $sThumbUrl . '" width="' . $imgwidth . '" height="' . $imgheight . '" alt="' . get_the_title($iPostID) . '" title="' . get_the_title($iPostID) . '" border="0"/>' .
                        '</a>';

        // Print the image
        echo $sImgString;
	}
}

function get_image_for_crop($postID)
{

    // Get the post ID
    $iPostID = $postID;

    // Get images for this post
    $arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );

    // If images exist for this page
    if($arrImages)
    {

        // Get array keys representing attached image numbers
        $arrKeys = array_keys($arrImages);

		/******BEGIN BUBBLE SORT BY MENU ORDER************
		// Put all image objects into new array with standard numeric keys (new array only needed while we sort the keys)
		foreach($arrImages as $oImage)
		{
			$arrNewImages[] = $oImage;

		}

		// Bubble sort image object array by menu_order TODO: Turn this into std "sort-by" function in functions.php
		for($i = 0; $i < sizeof($arrNewImages) - 1; $i++)
		{
			for($j = 0; $j < sizeof($arrNewImages) - 1; $j++)
			{
				if((int)$arrNewImages[$j]->menu_order > (int)$arrNewImages[$j + 1]->menu_order)
				{
					$oTemp = $arrNewImages[$j];
					$arrNewImages[$j] = $arrNewImages[$j + 1];
					$arrNewImages[$j + 1] = $oTemp;
				}
			}
		}

		// Reset arrKeys array
		$arrKeys = array();

		// Replace arrKeys with newly sorted object ids
		foreach($arrNewImages as $oNewImage)
		{
			$arrKeys[] = $oNewImage->ID;
		}
		******END BUBBLE SORT BY MENU ORDER**************/

        // Get the first image attachment
        $iNum = $arrKeys[0];

        $sImageUrl = wp_get_attachment_url($iNum);
        $sImageUrl=prepsimageurl($sImageUrl);


       return $sImageUrl;
	}
}


function prepsimageurl($src) {

	// remove http/ https/ ftp
	$src = preg_replace("/^((ht|f)tp(s|):\/\/)/i", "", $src);
	// remove domain name from the source url
	$host = $_SERVER["HTTP_HOST"];
	$src = str_replace($host, "", $src);
	$host = str_replace("www.", "", $host);
	$src = str_replace($host, "", $src);

	//$src = preg_replace( "/(?:^\/+|\.{2,}\/+?)/", "", $src );
	//$src = preg_replace( '/^\w+:\/\/[^\/]+/', '', $src );

	// don't allow users the ability to use '../'
	// in order to gain access to files below document root

	// src should be specified relative to document root like:
	// src=images/img.jpg or src=/images/img.jpg
	// not like:
	// src=../images/img.jpg
	$src = preg_replace( "/\.\.+\//", "", $src );

	return $src;

}

function get_height_of_image($src)
{

	$imgheight='';
    $doc_root = get_document_root($src);

	// get path to image on file system
	$src = $doc_root . $src;

	// get mime type of src
	$mime_type = mime_type($src);

	$image = open_image($mime_type, $src);

	if($image === false) {
	}
	else
	{

	// Get original width and height
	$width = imagesx($image);
	$imgheight = imagesy($image);

	}

	return $imgheight;

}

if (!function_exists('open_image'))
{

	function open_image($mime_type, $src)
	{



		if(stristr($mime_type, 'gif'))
		{

			$image = imagecreatefromgif($src);

		}
		elseif(stristr($mime_type, 'jpeg'))
		{

			@ini_set('gd.jpeg_ignore_warning', 1);
			$image = imagecreatefromjpeg($src);

		}
		elseif( stristr($mime_type, 'png'))
		{

			$image = imagecreatefrompng($src);

		}

		return $image;

	}

}

if (!function_exists('mime_type'))
{
	function mime_type($file)
	{
		$os = strtolower(php_uname());
		$mime_type = '';

		// use PECL fileinfo to determine mime type
		if( function_exists('finfo_open')) {
			$finfo = finfo_open(FILEINFO_MIME);
			$mime_type = finfo_file($finfo, $file);
			finfo_close($finfo);
		}

		// try to determine mime type by using unix file command
		// this should not be executed on windows
		if(!valid_src_mime_type($mime_type) && !(eregi('windows', $os))) {
			if(preg_match("/freebsd|linux/", $os)) {
				$mime_type = trim(@shell_exec('file -bi $file'));
			}
		}

		// use file's extension to determine mime type
		if(!valid_src_mime_type($mime_type)) {

			// set defaults
			$mime_type = 'image/jpeg';
			// file details
			$fileDetails = pathinfo($file);
			$ext = strtolower($fileDetails["extension"]);
			// mime types
			$types = array(
				'jpg'  => 'image/jpeg',
				'jpeg' => 'image/jpeg',
				'png'  => 'image/png',
				'gif'  => 'image/gif'
			);

			if(strlen($ext) && strlen($types[$ext])) {
				$mime_type = $types[$ext];
			}

		}

		return $mime_type;
	}
}

if (!function_exists('valid_src_mime_type'))
{

	function valid_src_mime_type($mime_type)
	{

		if(preg_match("/jpg|jpeg|gif|png/i", $mime_type))
		{
			return true;
		}
		return false;

	}
}

if (!function_exists('get_document_root'))
{
	function get_document_root ($src) {
		if( @file_exists( $_SERVER['DOCUMENT_ROOT'] . '/' . $src ) ) {
			return $_SERVER['DOCUMENT_ROOT'];
		}
		// the relative paths below are useful if timthumb is moved outside of document root
		// specifically if installed in wordpress themes like mimbo pro:
		// /wp-content/themes/mimbopro/scripts/timthumb.php
		$paths = array( '..', '../..', '../../..', '../../../..' );
		foreach( $paths as $path )
		{
			if( @file_exists( $path . '/' . $src ) )
			{
				return $path;
			}
		}

	}
}

// Handle Theme Options


// VARIABLES


$this_theme = "Aubogasta";
$themeoptionsprefix = "6609";
$options = array();
$sidebarpos=array('1','2');

$pathtothemetemplate = get_bloginfo('template_directory');

$menuico6609=$pathtothemetemplate.'/images/6609ico.png';

$options = array (

array("optionname" => "General Settings",
"optiontype" => "heading"),

array("optionname" => "Site Logo",
"optiondescription" => "<p>You can replace the text title with a logo by entering the logo URL here Note:include http://</p>",
"optionid" => $themeoptionsprefix."_sitelogo",
"selectoptiondef" => "",
"optiontype" => "text"),

array("optionname" => "Site Tracking Code Example: Google Analytics",
"optiondescription" => "<p>Using Goolge Analytics? You can enter your code below.</p>",
"optionid" => $themeoptionsprefix."_sitetrackingcode",
"selectoptiondef" => "",
"optiontype" => "textarea"),

array("optionname" => "Top Right Content",
"optiondescription" => "<p>Enter the code for the content you want to show in the gray box with the rounded corners at the top right of the page</p>",
"optionid" => $themeoptionsprefix."_wheelrightcontent",
"selectoptiondef" => "",
"optiontype" => "textarea"),

array("optionname" => "Sidebar Ad Code",
"optiondescription" => "<p>You can display adds in your sidebar. For best results use 250 pixels wide ad or 280 pixels wide ad</p>",
"optionid" => $themeoptionsprefix."_sidebarad",
"selectoptiondef" => "",
"optiontype" => "textarea"),


array("optionname" => "Twitter URL",
"optiondescription" => "<p>If you have a twitter page you can enter the URL here and a link will appear on the page</p>",
"optionid" => $themeoptionsprefix."_twitterurl",
"selectoptiondef" => "",
"optiontype" => "text"),

array("optionname" => "Feedburner RSS URL",
"optiondescription" => "<p>Your Feedburner URL</p>",
"optionid" => $themeoptionsprefix."_feedburnerurl",
"selectoptiondef" => "",
"optiontype" => "text"),

array("optionname" => "Feedburner ID",
"optiondescription" => "<p>Your Feedburner ID here.</p>",
"optionid" => $themeoptionsprefix."_feedburnerid",
"selectoptiondef" => "",
"optiontype" => "text"),

array("optionname" => "Header for Sidebar Subscribe Block",
"optiondescription" => "<p>The text to display as the header above the subscribe links in the sidebar.</p>",
"optionid" => $themeoptionsprefix."_rsssubscribeblockh2",
"selectoptiondef" => "",
"optiontype" => "text"),

array("optionname" => "Subtext for rss subscribe block",
"optiondescription" => "<p>The text to display as a short description for why to subscribe to your feed.</p>",
"optionid" => $themeoptionsprefix."_rsssubscribeblocksubtext",
"selectoptiondef" => "",
"optiontype" => "text"),

array("optionname" => "Subscribe Link Text",
"optiondescription" => "<p>The text to use for your subscribe link.</p>",
"optionid" => $themeoptionsprefix."_rsssubscribeblocklinktext",
"selectoptiondef" => "",
"optiontype" => "text"),


array("optionname" => "Sidebar Position - 1 for left/2 for right",
"optiondescription" => "You can make the sidebar display on the left of on the right.",
"optionid" => $themeoptionsprefix."_sidebarpos",
"selectoptiondef" => "Select a Number:",
"optiontype" => "select",
"options" => $sidebarpos),


);

function do_options_update_theme()
{
	global $this_theme, $options;

	if ( $_GET['page'] == basename(__FILE__) )
	{
		if ( 'updateoptions' == $_REQUEST['action'] )
		{

			foreach ($options as $optionvalue)
			{
				update_option( $optionvalue['optionid'], $_REQUEST[ $optionvalue['optionid'] ] );
			}

			foreach ($options as $optionvalue)
			{

					if( isset( $_REQUEST[ $optionvalue['optionid'] ] ) )
					{
						update_option( $optionvalue['optionid'], $_REQUEST[ $optionvalue['optionid'] ]  );
					}
					else
					{
						delete_option( $optionvalue['optionid'] );
					}

			}

			header("Location: admin.php?page=functions.php&optionsupdated=true");

			die;

		}
	}

	add_menu_page($this_theme." Options", $this_theme." Options", 'edit_themes', basename(__FILE__), 'do_page_6609', $menuico6609);
}

function do_page_6609 ()
{

	global $options, $this_theme;

?>

	<div class="wrap">

    <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">

	<h2><?php echo $this_theme; ?> Options</h2>

	<?php if ( $_REQUEST['optionsupdated'] ) { ?><?php echo "The options for $this_theme were saved";  } ?>

	<table>

<?php

		foreach ($options as $optionvalue)
		{

			if ( $optionvalue['optiontype'] <> "heading" )
			{

?>
				<tr>
				<td><?php echo $optionvalue['optionname']; ?></td>
				<td>
<?php
			}

				switch ( $optionvalue['optiontype'] )
				{
					case 'text':

?>
					<input name="<?php echo $optionvalue['optionid']; ?>" id="<?php echo $optionvalue['optionid']; ?>" type="<?php echo $optionvalue['optiontype']; ?>" value="<?php if ( get_settings( $optionvalue['optionid'] ) != "") { echo get_settings($optionvalue['optionid']); } else { echo $optionvalue['optionselectoptiondef']; } ?>" />

<?php

					break;
					case 'select':
?>
						<select name="<?php echo $optionvalue['optionid']; ?>" id="<?php echo $optionvalue['optionid']; ?>">
<?php

					foreach ($optionvalue['options'] as $option)
					{

?>
						<option<?php if ( get_settings( $optionvalue['optionid'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $optionvalue['optionselectoptiondef']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option>

<?php
					}

?>
						</select>

<?php
					break;
					case 'textarea':
					$textareainput = $optionvalue['options'];

?>
						<textarea name="<?php echo $optionvalue['optionid']; ?>" id="<?php echo $optionvalue['optionid']; ?>" cols="100" rows="8"><?php  if( get_settings($optionvalue['optionid']) != "") { echo stripslashes(get_settings($optionvalue['optionid'])); } else { echo $optionvalue['optionselectoptiondef']; } ?></textarea>
<?php

					break;
					case "heading":

?>
						</table>
   						<h3 class="title"><?php echo $optionvalue['optionname']; ?></h3>
						<table>

<?php

					break;
					default:
					break;

				}

?>

<?php

				if ( $optionvalue['optiontype'] <> "heading" )
				{

?>
					<span><?php echo $optionvalue['optiondescription']; ?></span>
					</td></tr>

<?php

				}

?>

<?php

			}

?>

					</table>

					<p class="submit">
					<input name="updateoptions" type="submit" value="Update Options" />
					<input type="hidden" name="action" value="updateoptions" />
					</p></form>
					</div>
<?php

}

add_action('admin_menu', 'do_options_update_theme');

?>