Create Order in prestashop programmatically - prestashop

I am trying to create an order in prestashop programmatically,
Here are the steps I am following:
$billingAddress = $order->getBillingAddress();
$shippingAddress = $order->getShippingAddress();
if (empty($billingAddress)) {
continue;
}
$id_customer = $this->createPrestashopCustomer($billingAddress, $order->getEmail());
$lines = $order->getLines();
$AddressObject = new AddressCore();
$AddressObject->id_customer = $id_customer;
$AddressObject->firstname = $billingAddress->getfirstName();
$AddressObject->lastname = $billingAddress->getlastName();
$AddressObject->address1 = " " . $billingAddress->getHouseNr();
$AddressObject->address1.= " " . $billingAddress->getHouseNrAddition();
$AddressObject->address1.= " " . $billingAddress->getStreetName();
$AddressObject->address1.= " " . $billingAddress->getZipCode();
$AddressObject->address1.= " " . $billingAddress->getCity();
$AddressObject->city = $billingAddress->getCity();
$AddressObject->id_customer = $id_customer;
$AddressObject->id_country = CountryCore::getByIso($billingAddress->getCountryIso());
$AddressObject->alias = ($billingAddress->getcompanyName() != "") ? "Company" : "Home";
$AddressObject->add();
$currency_object = new CurrencyCore();
$default_currency_object = $currency_object->getDefaultCurrency();
$id_currency = $default_currency_object->id;
$id_address = $AddressObject->id;
$cart = new Cart();
$cart->id_customer = (int) $id_customer;
$cart->id_address_delivery = $id_address;
$cart->id_address_invoice = $id_address;
$cart->id_lang = 1;
$cart->id_currency = (int) $id_address;
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
if (!empty($lines)) {
foreach ($lines as $item) {
$cart->updateQty(1, 5, 19);
}
}
$cart->update();
$order_object = new OrderCore();
$order_object->id_address_delivery = $id_address;
$order_object->id_address_invoice = $id_address;
$order_object->id_cart = $cart->id;
$order_object->id_currency = $id_currency;
$order_object->id_customer = $id_customer;
$CarrierObject = new CarrierCore();
$CarrierObject->delay[1] = "2-4";
$CarrierObject->active = 1;
$CarrierObject->name = "ChannelEngine Order2";
$CarrierObject->add();
$id_carrier = $CarrierObject->id;
$order_object->id_carrier = $id_carrier;
$order_object->payment = "Channel Engine Order";
$order_object->module = "1";
echo $order->getTotalInclVat();
$order_object->valid = 1;
$order_object->total_paid_tax_excl = $order->getTotalInclVat();
$order_object->total_discounts_tax_incl = $order->getTotalInclVat();
$order_object->total_paid = $order->getTotalInclVat();
$order_object->total_paid_real = $order->getTotalInclVat();
$order_object->total_products = $order->getSubTotalInclVat() - $order->getSubTotalVat();
$order_object->total_products_wt = $order->getSubTotalInclVat();
$order_object->conversion_rate = 1;
$order_object->id_shop = 1;
$order_object->id_lang = 1;
$order_object->secure_key = md5(uniqid(rand(), true));
$order_id = $order_object->add();
The Order is getting added to admin But somehow I can not see products in the order, Can anyone check and let me know what I am doing wrong here.
Also order total is also 0.

You should also create OrderDetail Objects for each product of this order.
Have a look at validateOrder() method of PaymentModule Class.
Here is an extract from this method:
$order = new Order();
$order->product_list = $package['product_list'];
if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
$address = new Address((int)$id_address);
$this->context->country = new Country((int)$address->id_country, (int)$this->context->cart->id_lang);
if (!$this->context->country->active) {
throw new PrestaShopException('The delivery address country is not active.');
}
}
$carrier = null;
if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
$carrier = new Carrier((int)$package['id_carrier'], (int)$this->context->cart->id_lang);
$order->id_carrier = (int)$carrier->id;
$id_carrier = (int)$carrier->id;
} else {
$order->id_carrier = 0;
$id_carrier = 0;
}
$order->id_customer = (int)$this->context->cart->id_customer;
$order->id_address_invoice = (int)$this->context->cart->id_address_invoice;
$order->id_address_delivery = (int)$id_address;
$order->id_currency = $this->context->currency->id;
$order->id_lang = (int)$this->context->cart->id_lang;
$order->id_cart = (int)$this->context->cart->id;
$order->reference = $reference;
$order->id_shop = (int)$this->context->shop->id;
$order->id_shop_group = (int)$this->context->shop->id_shop_group;
$order->secure_key = ($secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key));
$order->payment = $payment_method;
if (isset($this->name)) {
$order->module = $this->name;
}
$order->recyclable = $this->context->cart->recyclable;
$order->gift = (int)$this->context->cart->gift;
$order->gift_message = $this->context->cart->gift_message;
$order->mobile_theme = $this->context->cart->mobile_theme;
$order->conversion_rate = $this->context->currency->conversion_rate;
$amount_paid = !$dont_touch_amount ? Tools::ps_round((float)$amount_paid, 2) : $amount_paid;
$order->total_paid_real = 0;
$order->total_products = (float)$this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
$order->total_products_wt = (float)$this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
$order->total_discounts_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
$order->total_discounts_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
$order->total_discounts = $order->total_discounts_tax_incl;
$order->total_shipping_tax_excl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, false, null, $order->product_list);
$order->total_shipping_tax_incl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, true, null, $order->product_list);
$order->total_shipping = $order->total_shipping_tax_incl;
if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
$order->carrier_tax_rate = $carrier->getTaxesRate(new Address((int)$this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
}
$order->total_wrapping_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
$order->total_wrapping_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
$order->total_wrapping = $order->total_wrapping_tax_incl;
$order->total_paid_tax_excl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid_tax_incl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid = $order->total_paid_tax_incl;
$order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
$order->round_type = Configuration::get('PS_ROUND_TYPE');
$order->invoice_date = '0000-00-00 00:00:00';
$order->delivery_date = '0000-00-00 00:00:00';
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int)$id_cart, true);
}
// Creating order
$result = $order->add();
if (!$result) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int)$id_cart, true);
throw new PrestaShopException('Can\'t save Order');
}
// Amount paid by customer is not the right one -> Status = payment error
// We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
// if ($order->total_paid != $order->total_paid_real)
// We use number_format in order to compare two string
if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) {
$id_order_state = Configuration::get('PS_OS_ERROR');
}
$order_list[] = $order;
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int)$id_cart, true);
}
// Insert new Order detail list using cart for the current order
$order_detail = new OrderDetail(null, null, $this->context);
$order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
$order_detail_list[] = $order_detail;
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int)$id_cart, true);
}
// Adding an entry in order_carrier table
if (!is_null($carrier)) {
$order_carrier = new OrderCarrier();
$order_carrier->id_order = (int)$order->id;
$order_carrier->id_carrier = (int)$id_carrier;
$order_carrier->weight = (float)$order->getTotalWeight();
$order_carrier->shipping_cost_tax_excl = (float)$order->total_shipping_tax_excl;
$order_carrier->shipping_cost_tax_incl = (float)$order->total_shipping_tax_incl;
$order_carrier->add();
}

Create Order Programatically in prestashop, we need to use validate order function to create order manually in prestashop.
<?php
$cart = new Cart(Context::getContext()->cart);
$summary = $cart->getSummaryDetails($id_lang,true);
$total = (string) $summary['total_price'];
$cashondelivery = new CashOnDelivery();
if($cashondelivery->validateOrder((int) $cart->id,2, $total, $cashondelivery->displayName, null, array(),$id_currency, false, false)) {
$result['orderid']=(string)$cashondelivery->currentOrder;
return $result;
}

Related

Prestashop 1.7: product-prices.TPL: where is defined {$product.price_amount}?

I am looking at the file themes/my_theme/templates/catalog/_partials/product-prices.tpl. There, an attempt to show the real price with taxes is made: <span class="price-ttc">{Tools::displayPrice($product.price_amount*$prix_ttc)} TTC </span>.
However, I don't find the property named price_amount in web/controllers/front/ProductController.php:
public function getTemplateVarProduct()
{
$productSettings = $this->getProductPresentationSettings();
// Hook displayProductExtraContent
$extraContentFinder = new ProductExtraContentFinder();
$product = $this->objectPresenter->present($this->product);
$product['id_product'] = (int) $this->product->id;
$product['out_of_stock'] = (int) $this->product->out_of_stock;
$product['new'] = (int) $this->product->new;
$product['id_product_attribute'] = $this->getIdProductAttributeByRequestOrGroup();
$product['minimal_quantity'] = $this->getProductMinimalQuantity($product);
$product['quantity_wanted'] = $this->getRequiredQuantity($product);
$product['extraContent'] = $extraContentFinder->addParams(array('product' => $this->product))->present();
$product['ecotax'] = Tools::convertPrice((float) $product['ecotax'], $this->context->currency, true, $this->context);
$product_full = Product::getProductProperties($this->context->language->id, $product, $this->context);
$product_full = $this->addProductCustomizationData($product_full);
$product_full['show_quantities'] = (bool) (
Configuration::get('PS_DISPLAY_QTIES')
&& Configuration::get('PS_STOCK_MANAGEMENT')
&& $this->product->quantity > 0
&& $this->product->available_for_order
&& !Configuration::isCatalogMode()
);
$product_full['quantity_label'] = ($this->product->quantity > 1) ? $this->trans('Items', array(), 'Shop.Theme.Catalog') : $this->trans('Item', array(), 'Shop.Theme.Catalog');
$product_full['quantity_discounts'] = $this->quantity_discounts;
if ($product_full['unit_price_ratio'] > 0) {
$unitPrice = ($productSettings->include_taxes) ? $product_full['price'] : $product_full['price_tax_exc'];
$product_full['unit_price'] = $unitPrice / $product_full['unit_price_ratio'];
}
$group_reduction = GroupReduction::getValueForProduct($this->product->id, (int) Group::getCurrent()->id);
if ($group_reduction === false) {
$group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
}
$product_full['customer_group_discount'] = $group_reduction;
$product_full['title'] = $this->getProductPageTitle();
$presenter = $this->getProductPresenter();
return $presenter->present(
$productSettings,
$product_full,
$this->context->language
);
}
Could you please tell me where is it located?
PrestaShop 1.7 uses Presenters
Your property is defined here:
/src/Adapter/Presenter/Product/ProductLazyArray.php in addPriceInformation method

How to save data in db

In user table, the data stored in db as well as resize the images in folders.
But the usergallary table same functionality didn't work only image resized in the folders but not stored in db.
public function actionProfileImage($id) {
$userModel = User::model()->findByAttributes(array('id' => $id));
$userGallary = new UserGallary;
$filePrefix = Yii::app()->params['profile']['prefix'];
$targetImagePath = Yii::app()->params['profile']['image']['path'];
$target150Path = Yii::app()->params['profile']['thumb150']['path'];
$target25Path = Yii::app()->params['profile']['thumb25']['path'];
if (isset($_FILES['uploaded_picture'])) {
$handle = new Upload($_FILES['uploaded_picture']);
if ($handle->uploaded) {
$handle->file_name_body_pre = $filePrefix;
$handle->process($targetImagePath);
if ($handle->processed) {
$handle->file_name_body_pre = $filePrefix;
$handle->image_resize = true;
$handle->image_x = 150;
$handle->image_y = 150;
//$handle->image_ratio_y = true;
$handle->image_ratio = true;
$handle->process($target150Path);
if ($handle->processed) {
$handle->file_name_body_pre = $filePrefix;
$handle->image_resize = true;
$handle->image_x = 25;
$handle->image_y = 25;
// $handle->image_ratio_y = true;
$handle->image_ratio = true;
var_dump($$target150Path);exit;
$handle->process($target25Path);
if ($handle->processed) {
$userGallary->uploaded_picture = "{$filePrefix}.{$handle->file_dst_name_ext}";
$userGallary->save();
}
}
$handle->clean();
}
}
}
echo CJSON::encode( arraY('path150' => $target150Path,
'file' => $userGallary->uploaded_picture,
));
}

extracting information from NSDictionary

I have a NSDictionary response from a Flickr api request and it's description looks like this:
self.userInfo: {
"_text" = "\n\n";
person = {
"_text" = "\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n";
description = {
};
iconfarm = 0;
iconserver = 0;
id = "83943196#N02";
ispro = 0;
location = {
};
"mbox_sha1sum" = {
"_text" = 7b61c5d24f12345678be82c31234567830540;
};
mobileurl = {
"_text" = "http://m.flickr.com/photostream.gne?id=12345678";
};
nsid = "12345678#N02";
"path_alias" = "";
photos = {
"_text" = "\n\t\t\n\t\t\n\t\t\n\t\t\n\t";
count = {
"_text" = 2;
};
firstdate = {
"_text" = 12345678;
};
firstdatetaken = {
"_text" = "2012-08-01 12:46:38";
};
views = {
"_text" = 0;
};
};
photosurl = {
"_text" = "http://www.flickr.com/photos/12345678#N02/";
};
profileurl = {
"_text" = "http://www.flickr.com/people/12345678#N02/";
};
realname = {
"_text" = "Me TheUser";
};
timezone = {
label = "Pacific Time (US & Canada); Tijuana";
offset = "-08:00";
};
username = {
"_text" = metheuser;
};
};
stat = ok;
}
I'm having truoble figuring out how to extract the realname value into a NSString.
I've tried:
NSString * temp = [self.userInfo valueForKey:#"realname"];
NSLog (#"FL: nameOfSignedInUser. nameself.userInfo: %#", temp.debugDescription);
but that comes back as nil.
thank you!
NSString *name = [self.userInfo valueForKeyPath:#"person.realname._text"];
NSString *realName = [[[self.userInfo objectForKey:#"person"] objectForKey:#"realname"] objectForKey:#"_text"];

How best to traverse API information with iOS

Is there any easier way of traversing array/dictionaries without creating a lot of separate NSArrays/NSDictionaries? I know you can traverse nested dictionaries with dot notation and value at keypath, but what about when arrays are involved?
For example:
At the moment if I want to get at the object at feed.entry.link[4].href in the API result below, I have to define an array at keypath "feed.entry", then assign its first entry as a dictionary, then define an array at keypath "link" and access its fourth entry as a dictionary, and then access its value at "href".
Is this normal?
received {
encoding = "UTF-8";
feed = {
entry = (
{
author = (
{
name = {
"$t" = swdestiny;
};
uri = {
"$t" = "https://gdata.youtube.com/feeds/api/users/swdestiny";
};
}
);
category = (
{
scheme = "http://schemas.google.com/g/2005#kind";
term = "http://gdata.youtube.com/schemas/2007#video";
},
{
label = Entertainment;
scheme = "http://gdata.youtube.com/schemas/2007/categories.cat";
term = Entertainment;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = Star;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = Wars;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = Episode;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = 3;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = Revenge;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = of;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = the;
},
{
scheme = "http://gdata.youtube.com/schemas/2007/keywords.cat";
term = Sith;
}
);
content = {
"$t" = "sw-destiny.net Trailer for Revenge of the Sith";
type = text;
};
"gd$comments" = {
"gd$feedLink" = {
countHint = 1567;
href = "https://gdata.youtube.com/feeds/api/videos/9kdEsZH5ohc/comments";
rel = "http://gdata.youtube.com/schemas/2007#comments";
};
};
"gd$rating" = {
average = "4.7729683";
max = 5;
min = 1;
numRaters = 1132;
rel = "http://schemas.google.com/g/2005#overall";
};
id = {
"$t" = "http://gdata.youtube.com/feeds/api/videos/9kdEsZH5ohc";
};
link = (
{
href = "https://www.youtube.com/watch?v=9kdEsZH5ohc&feature=youtube_gdata";
rel = alternate;
type = "text/html";
},
{
href = "https://gdata.youtube.com/feeds/api/videos/9kdEsZH5ohc/responses";
rel = "http://gdata.youtube.com/schemas/2007#video.responses";
type = "application/atom+xml";
},
{
href = "https://gdata.youtube.com/feeds/api/videos/9kdEsZH5ohc/related";
rel = "http://gdata.youtube.com/schemas/2007#video.related";
type = "application/atom+xml";
},
{
href = "https://m.youtube.com/details?v=9kdEsZH5ohc";
rel = "http://gdata.youtube.com/schemas/2007#mobile";
type = "text/html";
},
{
href = "https://gdata.youtube.com/feeds/api/videos/9kdEsZH5ohc";
rel = self;
type = "application/atom+xml";
}
);
"media$group" = {
"media$category" = (
{
"$t" = Entertainment;
label = Entertainment;
scheme = "http://gdata.youtube.com/schemas/2007/categories.cat";
}
);
"media$content" = (
{
duration = 151;
expression = full;
isDefault = true;
medium = video;
type = "application/x-shockwave-flash";
url = "https://www.youtube.com/v/9kdEsZH5ohc?version=3&f=videos&app=youtube_gdata";
"yt$format" = 5;
},
{
duration = 151;
expression = full;
medium = video;
type = "video/3gpp";
url = "rtsp://v2.cache4.c.youtube.com/CiILENy73wIaGQkXovmRsURH9hMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
"yt$format" = 1;
},
{
duration = 151;
expression = full;
medium = video;
type = "video/3gpp";
url = "rtsp://v2.cache5.c.youtube.com/CiILENy73wIaGQkXovmRsURH9hMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
"yt$format" = 6;
}
);
"media$description" = {
"$t" = "sw-destiny.net Trailer for Revenge of the Sith";
type = plain;
};
"media$keywords" = {
"$t" = "Star, Wars, Episode, 3, Revenge, of, the, Sith";
};
"media$player" = (
{
url = "https://www.youtube.com/watch?v=9kdEsZH5ohc&feature=youtube_gdata_player";
}
);
"media$thumbnail" = (
{
height = 360;
time = "00:01:15.500";
url = "http://i.ytimg.com/vi/9kdEsZH5ohc/0.jpg";
width = 480;
},
{
height = 90;
time = "00:00:37.750";
url = "http://i.ytimg.com/vi/9kdEsZH5ohc/1.jpg";
width = 120;
},
{
height = 90;
time = "00:01:15.500";
url = "http://i.ytimg.com/vi/9kdEsZH5ohc/2.jpg";
width = 120;
},
{
height = 90;
time = "00:01:53.250";
url = "http://i.ytimg.com/vi/9kdEsZH5ohc/3.jpg";
width = 120;
}
);
"media$title" = {
"$t" = "Star Wars Episode 3 Revenge of the Sith Trailer";
type = plain;
};
"yt$duration" = {
seconds = 151;
};
};
published = {
"$t" = "2007-05-23T03:31:54.000Z";
};
title = {
"$t" = "Star Wars Episode 3 Revenge of the Sith Trailer";
type = text;
};
updated = {
"$t" = "2012-02-20T17:14:37.000Z";
};
"yt$statistics" = {
favoriteCount = 763;
viewCount = 796719;
};
}
);
xmlns = "http://www.w3.org/2005/Atom";
"xmlns$gd" = "http://schemas.google.com/g/2005";
"xmlns$media" = "http://search.yahoo.com/mrss/";
"xmlns$yt" = "http://gdata.youtube.com/schemas/2007";
};
version = "1.0";
}

How to manage depth in AS2

How do I change the movie clip (mainClip) in AS2 code below so that is behind all graphics in the flash file?
Code is below:
import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.geom.Point;
var imageBmp:BitmapData;
//setting the width of blind parts.
var widthB:Number = 40;
//setting the speed of blind parts movement;
var speedChart = 5;
//time to wait lo load another image
var nbSpeedPhoto:Number = 3000;
//Setting the minimum and maximum alpha for controls container and updating timer
var nbACMin:Number = 10;
var nbACMax:Number = 65;
var nbACUpd:Number = 40;
//Setting the minimum and maximum alpha for textField Container
var nbATMin:Number = 0;
var nbATMax:Number = 100;
var nbABMin:Number = 0;
var nbABMax:Number = 65;
//Setting the color for textField Container and font title
var nbATBackColor:Number = 0xD0C8CD;
var nbATFontColor:Number = 0x1F0010;
//Setting the right margin and top margin for controls
var nbRightMC:Number = 2;
var nbTopMC:Number = 2;
//Setting the bottom margin for title and its height
var nbBottomMT:Number = 5;
var nbHeightMT:Number = 50;
//Init Slider viewer
var bbPlay:Boolean = true;
//Setting left to right (1), right to left (2), paralell(3), or random(4) transition
var nbForm:Number = 4;
//if you don't choose parallel, setting the time lag.
var nbLag:Number = 1;
//initial state of FullScreen and AutoPlaying buttons
var bbFull:Boolean = false;
var bbAnimating:Boolean = false;
var bbEnableTitle:Boolean = false;
var bbActiveTitle:Boolean = false;
//setting the first image number to load
var imageNum:Number = 0;
var imageLast:Number;
//initial Photo
var nbPhoto:Number = 0;
//timer variables
var nbTimerNow:Number = 0;
var nbTimerNext:Number = nbSpeedPhoto;
/*********Arrays*******************/
//used for load XML values
var arPhotoPath:Array = new Array();
var arPhotoTitle:Array = new Array();
/**Setting listener to load images**********/
var listener:Object = new Object();
listener.onLoadComplete = function(imageClip:MovieClip):Void {
if (imageNum>0) {
imageBmp = new BitmapData(mainClip["image"+imageLast]._width, mainClip["image"+imageLast]._height);
imageBmp.draw(mainClip["image"+imageLast],new Matrix());
var sqBmp:BitmapData;
var x:Number = 0;
var y:Number = 0;
if (nbForm == 1 || nbForm == 2 || nbForm == 3) {
form = nbForm;
} else {
rnd=Math.random()
if (rnd>0.66) {
form = 1;
} else if (rnd>0.33){
form = 2;
}else{
form = 3;
}
}
for (var j:Number = 0; j<cols; j++) {
x = j*widthB;
if (j>=cols-1) {
var ww = Stage.width-j*widthB;
} else {
var ww = widthB;
}
sqBmp = new BitmapData(ww, mcMask._height);
sqBmp.copyPixels(imageBmp,new Rectangle(x, y, ww, mcMask._height),new Point(0, 0));
cloneClip.createEmptyMovieClip("clone"+imageLast,cloneClip.getNextHighestDepth());
makeSq(sqBmp,j,form);
}
}
unloadMovie(mainClip["image"+imageLast]);
bbAnimating = false;
bbEnableTitle = true;
nbTimerNext = getTimer()+nbSpeedPhoto;
nbOK = 0;
mcText.tfToolTip.text = "Photo "+String(nbPhoto+1)+" of "+String(xmlLength)+": "+arPhotoTitle[nbPhoto];
mcText.tfToolTip.setTextFormat(myformat);
imageNum++;
};
var imageLoader:MovieClipLoader = new MovieClipLoader();
imageLoader.addListener(listener);
/***Creating Squares*******/
function makeSq(sqBmp:BitmapData, jValue:Number, fvalue:Number):Void {
var sqClip:MovieClip = cloneClip["clone"+imageLast].createEmptyMovieClip("sq"+jValue, cloneClip["clone"+imageLast].getNextHighestDepth());
sqClip.attachBitmap(sqBmp,1);
sqClip._x = jValue*widthB;
if (fvalue == 1) {
sqClip.lag = jValue;
} else if(fvalue == 2) {
sqClip.lag = cols-jValue;
}else{
sqClip.lag = 0;
}
sqClip.init = 0;
sqClip.onEnterFrame = function() {
if (this.init>this.lag) {
this._xscale = this._xscale-speedChart;
}
this.init += nbLag;
if (this._yscale<0 || this._xscale<0) {
unloadMovie(this);
}
};
}
//setting the main movieclip and its clone.
//the clone will store the parts of the main image.
this.createEmptyMovieClip("mainClip",this.getNextHighestDepth());
this.createEmptyMovieClip("cloneClip",this.getNextHighestDepth());
this.createEmptyMovieClip("mcMask",this.getNextHighestDepth());
this.createEmptyMovieClip("mcMask2",this.getNextHighestDepth());
//Creating the text container and setting its properties
this.createEmptyMovieClip("mcText",this.getNextHighestDepth());
mcText.createEmptyMovieClip("mcBackText",this.getNextHighestDepth());
makeARectangle(mcText.mcBackText,0,Stage.height-nbBottomMT-nbHeightMT,Stage.width,nbHeightMT,nbATBackColor,100);
mcText.mcBackText._alpha = 0;
//Creating the mc text container
mcText.createTextField("tfToolTip",mcText.getNextHighestDepth(),0,Stage.height-nbBottomMT-nbHeightMT,Stage.width,nbHeightMT);
mcText.tfToolTip._alpha = 0;
//Creating the masks
var bmpMask:BitmapData = new BitmapData(Stage.width, Stage.height, false, 0xCCCCCC);
mcMask.attachBitmap(bmpMask,this.getNextHighestDepth());
mcMask2.attachBitmap(bmpMask,this.getNextHighestDepth());
mainClip.createEmptyMovieClip("image"+imageNum,this.getNextHighestDepth());
//setting the number of columns and files
var cols = Math.ceil(mcMask._width/widthB);
//setting the main and clone masks
mainClip.setMask(mcMask2);
cloneClip.setMask(mcMask);
//setting buttons behaviors
if (bbPlay) {
mcControl.mcPausePlay.gotoAndStop("onPlay");
} else {
mcControl.mcPausePlay.gotoAndStop("onPause");
}
mcControl.mcBackControls.onRollOver = mcControl.mcFull.onRollOver=mcControl.mcLast.onRollOver=mcControl.mcFirst.onRollOver=mcControl.mcPrevious.onRollOver=mcControl.mcPausePlay.onRollOver=mcControl.mcNext.onRollOver=function () {
clearInterval(activeID);
activeID = setInterval(activeControl, nbACUpd, true);
};
mcControl.mcBackControls.onRollOut = mcControl.mcFull.onRollOut=mcControl.mcLast.onRollOut=mcControl.mcFirst.onRollOut=mcControl.mcPrevious.onRollOut=mcControl.mcPausePlay.onRollOut=mcControl.mcNext.onRollOut=function () {
clearInterval(activeID);
activeID = setInterval(activeControl, nbACUpd, false);
};
function activeControl(bb:Boolean) {
if (bb) {
if (mcControl._alpha>=nbACMax) {
clearInterval(activeID);
} else {
mcControl._alpha += 4;
}
} else {
if (mcControl._alpha<nbACMin) {
clearInterval(activeID);
} else {
mcControl._alpha -= 4;
}
}
}
mcControl.mcFull.onRelease = function() {
if (bbFull) {
Stage.displayState = "normal";
this.gotoAndStop("onNormal");
bbFull = false;
} else {
Stage.displayState = "fullScreen";
this.gotoAndStop("onFull");
bbFull = true;
}
};
mcControl.mcPausePlay.onRelease = function() {
if (bbPlay) {
this.gotoAndStop("onPause");
bbPlay = false;
clearInterval(initPhoto);
} else {
if (!bbAnimating) {
this.gotoAndStop("onPlay");
bbPlay = true;
clearInterval(initPhoto);
initPhoto = setInterval(initPlay, 200);
}
}
};
mcControl.mcLast.onRelease = mcControl.mcFirst.onRelease=mcControl.mcPrevious.onRelease=mcControl.mcNext.onRelease=function () {
if (bbAnimating == false) {
clearInterval(initPhoto);
mcControl.mcPausePlay.gotoAndStop("onPause");
bbPlay = false;
mcControl.mcPausePlay.onRelease;
switch (this._name) {
case "mcFirst" :
nbPhoto = 0;
break;
case "mcPrevious" :
nbPhoto = (xmlLength+nbPhoto-1)%xmlLength;
break;
case "mcNext" :
nbPhoto = (nbPhoto+1)%xmlLength;
break;
case "mcLast" :
nbPhoto = xmlLength-1;
break;
default :
break;
}
imageLast = imageNum-1;
mainClip.createEmptyMovieClip("image"+imageNum,mainClip.getNextHighestDepth());
imageLoader.loadClip(arPhotoPath[nbPhoto],mainClip["image"+imageNum]);
bbAnimating == true;
}
};
/********************************/
function makeEnabled(bbEnable:Boolean) {
with (mcControl) {
mcPausePlay.enabled = bbEnable;
mcLast.enabled = bbEnable;
mcFirst.enabled = bbEnable;
mcPrevious.enabled = bbEnable;
mcNext.enabled = bbEnable;
}
}
function makeVisible(bbVisible:Boolean) {
with (mcControl) {
mcPausePlay.enabled = bbVisible;
mcLast.enabled = bbVisible;
mcFirst.enabled = bbVisible;
mcPrevious.enabled = bbVisible;
mcNext.enabled = bbVisible;
}
}
function initPlay() {
if (bbAnimating == false) {
if (bbPlay) {
if (getTimer()>=nbTimerNext) {
nbPhoto = (nbPhoto+1)%xmlLength;
imageLast = imageNum-1;
mainClip.createEmptyMovieClip("image"+imageNum,mainClip.getNextHighestDepth());
imageLoader.loadClip(arPhotoPath[nbPhoto],mainClip["image"+imageNum]);
bbAnimating = true;
nbTimerNext += nbSpeedPhoto;
}
}
}
}
var myformat:TextFormat = new TextFormat();
myformat.font = "myFont";
myformat.color = nbATFontColor;
myformat.size = 18;
mcText.tfToolTip.embedFonts = true;
mcText.tfToolTip.wordWrap = true;
mcText.onRollOver = function() {
if (bbEnableTitle && !bbAnimating) {
alphaTitle(nbATMax,nbABMax);
bbActiveTitle = true;
}
};
mcText.onRollOut = function() {
if (bbEnableTitle) {
alphaTitle(nbATMin,nbABMin);
bbActiveTitle = false;
}
};
function alphaTitle(nbTextAlpha:Number, nbBackAlpha) {
mcText.mcBackText._alpha = nbBackAlpha;
mcText.tfToolTip._alpha = nbTextAlpha;
mcText.tfToolTip.setTextFormat(myformat);
}
//drawing a square
function makeARectangle(mc:MovieClip, x:Number, y:Number, w:Number, h:Number, nbColor:Number, nbAlpha:Number) {
mc.lineStyle(1,nbColor,0);
mc.beginFill(nbColor,nbAlpha);
mc.moveTo(x,y);
mc.lineTo(x+w,y);
mc.lineTo(x+w,y+h);
mc.lineTo(x,y+h);
mc.lineTo(x,y);
mc.endFill();
}
//for loading external XML
var xmlPhotos:XML = new XML();
xmlPhotos.onLoad = function() {
xmlLength = this.firstChild.childNodes.length;
for (var i:Number = 0; i<xmlLength; i++) {
arPhotoPath[i] = (this.firstChild.childNodes[i].attributes.path);
arPhotoTitle[i] = (this.firstChild.childNodes[i].childNodes[0].firstChild.nodeValue);
}
imageLoader.loadClip(arPhotoPath[0],mainClip["image"+imageNum]);
bbAnimating = true;
initPhoto = setInterval(initPlay, 200);
};
/****Run XML*****************************************/
xmlPhotos.ignoreWhite = true;
xmlPhotos.load("photos.xml");
mainClip.swapDepths(1);
you need to make sure that all the movieclips are on the same layer on the timeline.